JS容易忘记或混淆的点

array.prototype

  1. array splice 改变原数组,返回弹出的元素数组
  2. array/string slice 不改变原数组,返回截取的元素数组
  3. array push 改变原数组,返回新的数组长度(在数组后面新增)
  4. array pop 改变原数组,返回弹出的值(数组最后一个值)
  5. array/string concat 不改变原数组,返回新的数组
  6. array shift 改变原数组,返回弹出的值(数组第一个值,类似pop)
  7. array unshift 改变原数组,返回数组长度(在数组前面新增,类似push)
  8. array/string indexOf(item) 返回array/string中首次出现item的位置
  9. array/string lastIndexOf(item) 返回array/string中最后一次出现item的位置
  10. array reverse 改变原数组,返回改变后的数组
// 直接修改item并不会修改原数组
var a = [1,2,3]
a.forEach(function(item) {
  item += 1
})
// a [1, 2, 3] 

var a = [1,2,3]
a.forEach(function(item,idx) {
  a[idx] += 1
})
// a [2, 3, 4]

string.prototype

  1. string substr(start, len) 不改变原字符串,返回截取的字符串
  2. string substring(start, end) 不改变原字符串,返回截取的字符串
  3. array/string concat 不改变原字符串,返回新的字符串
  4. array/string slice 不改变原字符串,返回截取的字符串
  5. string也可以像array一样直接通过下标获取值
  6. array/string indexOf(item) 返回array/string中首次出现item的位置
  7. array/string lastIndexOf(item) 返回array/string中最后一次出现item的位置

number.prototype

number.toString(radix) 可以直接转换进制

var count = 10;
console.log(count.toString());    // displays '10'
console.log((17).toString());     // displays '17'
console.log((17.2).toString());   // displays '17.2'

var x = 6;
console.log(x.toString(2));       // displays '110'
console.log((254).toString(16));  // displays 'fe'

console.log((-10).toString(2));   // displays '-1010'
console.log((-0xff).toString(2)); // displays '-11111111'

object.prototype

var o = new Object();
o.toString(); // returns [object Object]

function Dog(name, breed, color, sex) {
  this.name = name;
  this.breed = breed;
  this.color = color;
  this.sex = sex;
}
theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
theDog.toString(); // returns [object Object]
Dog.prototype.toString = function dogToString() {
  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
  return ret;
}

function

function functions(flag) {
    if (flag) {
      function getValue() { return 'a'; }// 函数声明,输出b(然而事实上chrome下依然输出a)
      var getValue = function () { return 'a'; }// 函数表达式,输出a
    } else {
      function getValue() { return 'b'; }// 函数声明,输出b
      var getValue = function () { return 'b'; }// 函数表达式,输出b
    }
    return getValue();
}

函数声明:解析器会率先读取并且让其在执行任何代码前可用,意思就是别的代码还没运行呢,两个getValue声明已经被读取,所以总是执行最新的那个。
函数表达式:当解析器执行到它所在的代码行时,才会真正被解释执行,所以两个逻辑分支可以分别执行

parseInt

parseInt(string, radix) 当参数 radix 的值为 0,或没有设置该参数时,parseInt() 会根据 string 来判断数字的基数

当参数 radix 的值为 0,或没有设置该参数时,parseInt() 会根据 string 来判断数字的基数。当字符以0x开头,可能转换为16进制。以0开头可能转化8进制。当基数设置为10的时候,遇到非数字字符会直接忽略后面的字符

timer计时器

setTimeout(func, time) 返回计时器id,开启计时器
clearTimeout(timerId) 取消计时器
setInterval(func, time) 返回计时器id,开启计时器
clearInterval(timerId) 取消计时器

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容