# 一、数组操作方法

常用普通方法:

方法名 作用 是否改变原数组
push/pop 入栈弹栈 改变之后长度/弹出元素
shift/unshift 删除第1项/插入第1项 队列出来的元素/长度
sort 排序
reverse 反转数组
contact 连接数组

# 1.1join

功能:将数组变为一个字符串,参数就是分隔符

参数:字符串,代表分隔符

是否改变原数组:否

let arr = [1,2,3]	// 原数组
console.log(arr.join('-'))	// 新字符串 1-2-3
console.log(arr)	// [1,2,3] 原数组未改变

# 1.2slice

作用:返回从原数组中指定开始下标到结束下标之间项的新数组

参数:一个或两个;开始位置,结束位置

是否改变原数组:否

当参数为负数时,加上数组长度转换成正数

区间:左闭右开

let arr = [1,2,3,4,5,6,7]  // 原数组

console.log(arr.slice(1)) 	//[ 2, 3, 4, 5, 6, 7 ] 从第一个开始到结束

console.log(arr.slice(1,4))	//

console.log(arr.slice(-4,-1))

console.log(arr)

# 1.3splice

splice(index,length,增加的元素1,增加的元素2....,增加的元素N)

作用:表示从index开始删除length个元素

返回值:被删除的元素组成的数组

是否改变原数组:是

var a = [1,2,3]
var b = a.splice(1,1,3,[2,3,4],5)
 
console.log(a)  // [1,3,[2,3,4],5,3]
console.log(b)  // [2]

# 1.4 indexOf(某元素,startIndex)

作用:从startIndex开始,查找某个元素,找到返回第一个位置的下标,否则返回-1

返回值:第一找到元素的下标||-1

是否改变原数组:否

var a = [1,2,4,3,4,5]
 
console.log(a.indexOf(4))  // 2
console.log(a.indexOf(4,3)) // 4
console.log(a) // 原数组

# 1.5filter

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

第一个参数回调函数,包含三个参数: 元素、下标、原数组;第二个参数为当前this

作用:过滤数组中的元素

是否改变原数组:否

返回值:通过过滤的新数组

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result); // [ 'exuberant', 'destruction', 'present' ]

console.log(words) 	// 元数组

# 1.6map

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

作用:遍历原数组进行相关处理返回新数组

参数:两个,第一个callback,第二个this

返回值:新数组

是否修改原数组:否

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

# 1.7reduce

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

作用:累加器

参数:第一个回调函数,第二个初始值;回调函数四个参数:当前累加值、当前值、当前索引、原数组

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

# isArray

作用:判断是否为数组

参数:需要被判断的元素

返回值:布尔值

# 二、字符串

# 1.includes

作用:查看该字符串是否包含当前参

返回值:布尔值

'Blue Whale'.includes('blue'); // returns false

# 2. indexOf

str.indexOf(searchValue [, fromIndex])

作用:从下表fromIndex开始,查找searchValue找到返回下表

参数:第一个被查找字符串,第二个从哪里开始查(默认为0)

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// expected output: "The index of the first "dog" from the beginning is 40"

console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// expected output: "The index of the 2nd "dog" is 52"

# 3.replace

str.replace(regexp|substr, newSubStr|function)

作用:将substr替换成newSubStr

是否修改原字符串:否

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

const regex = /dog/gi;

console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

# 4.replaceAll

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

作用:返回新字符串

是否修改原字符串:否

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

const regex = /dog/gi;

console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"

# 5.slice

str.slice(beginIndex[, endIndex])

作用: 方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。

是否修改原字符串:否

参数:开始值;结束值(默认到最后)

规则:左闭右开,若参数为负数,则加上长度变为正数

const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// expected output: "the lazy dog."

console.log(str.slice(4, 19));
// expected output: "quick brown fox"

console.log(str.slice(-4));
// expected output: "dog."

console.log(str.slice(-9, -5));
// expected output: "lazy"

# 6.substr

: : : warning

警告:该方法可能会被移除,应避免使用,用substring代替

: : :

str.substr(start[, length])

作用:返回指定位置开始到指定字符串数的字符串

参数:开始位置,截取个数

改变?否

var str = "abcdefghij";

console.log("(1,2): "    + str.substr(1,2));   // (1,2): bc
console.log("(-3,2): "   + str.substr(-3,2));  // (-3,2): hi
console.log("(-3): "     + str.substr(-3));    // (-3): hij
console.log("(1): "      + str.substr(1));     // (1): bcdefghij
console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
console.log("(20, 2): "  + str.substr(20,2));  // (20, 2):

# 7.str.substring(indexStart[, indexEnd])

作用:返回开始索引到结束索引的子集

参数:indexStart、indexStart(默认到最后)

规则:

  • 如果 indexStart 等于 indexEndsubstring 返回一个空字符串。
  • 如果省略 indexEndsubstring 提取字符一直到字符串末尾。
  • 如果任一参数小于 0 或为 [NaN],则被当作 0。
  • 如果任一参数大于 stringName.length,则被当作 stringName.length
  • 如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样。见下面的例子。
var anyString = "Mozilla";

// 输出 "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));
console.log(anyString.substring(-2,3));
console.log(anyString.substring(NaN,3));

// 输出 "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));

// 输出 ""
console.log(anyString.substring(4,4));

// 输出 "Mozill"
console.log(anyString.substring(0,6));

// 输出 "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));

# 8.toLowerCase

作用:直接转化成小写

是否改变源字符串:否

console.log('中文简体 zh-CN || zh-Hans'.toLowerCase());
// 中文简体 zh-cn || zh-hans

console.log( "ALPHABET".toLowerCase() ); 
// "alphabet"

# 9. toUpperCase

与转换小写类似

# 10.charCodeAt & fromCharCode

  • 65代表A,97代表a

charCodeAt 把字母转换成码,fromCharCode把码转换成字母

var toLowerCase = function(str) {
  let ret = ''
  for(let i = 0; i < str.length; i++){
    let code = str.charCodeAt(i)
    console.log(code)
    if(code <= 90 && code>=65){
      ret += String.fromCharCode(code + 32)
    }else{
      ret += str[i]
    }
  }
  return ret
};

# 三、对象

# 1. assign

作用:复制对象

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

# 2. create

作用:创建新对象

const person = {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

# 3. defineProperties

作用: 直接在一个对象上定义新的属性或修改现有属性,并返回该对象。

语法:Object.defineProperties(obj, props)

参数:

obj

在其上定义或修改属性的对象。

props

要定义其可枚举属性或修改的属性描述符的对象。对象中存在的属性描述符主要有两种:数据描述符和访问器描述符。描述符具有以下键:

# 4.toString

# 5. hasOwnProperty

# 6.defineProperty

作用:监听改变对象对应key的值

语法: Object.defineProperty(obj,key,{})大货号里面写get set函数

参数:obj是对象,key是obj对应的key,{}里面是get set

例子:

  • set函数监听到数据改变,他要告诉需要用的人(谁触发了get就是谁在用)
  • get函数谁用了输了数据就会触发get函数
let obj = {
  name: 'qmj',
  age: 18
}

Object.keys(obj).forEach(key => {
  let value = obj[key]

  Object.defineProperty(obj,key,{
    set(newValue){
      console.log('监听'+key+'改变')
      value = newValue
    },
    get(){
      console.log('获取'+key+'的值')
      return value // 改变值
    }
  })
})

obj.name = 'qqqq'  // 修改属性时,会触发set函数
console.log(obj.name)  // 获取属性时,会触发get函数

# 7.keys

作用:返回一个由给定对象的自身可枚举属性组成的数组,数组的排列顺序和正常遍历对象一致

语法:Object.keys(obj)

参数:obj 对应的对象

let obj = {
  name: 'qmj',
  age: 18
}


console.log(Object.keys(obj)) // ['name','age']
最后更新于: 12/25/2020, 9:20:27 AM