Commonly used array methods in js

String methods

indexOf() : Search for the position where the first string appears

var str = 'hi weianl    !哈哈哈';
str.indexOf('h'); // 返回0,从0开始
str.indexOf('i'); // 返回1,首个字符串
str.indexOf('weianl'); // 返回3,空格键占1
str.indexOf('!'); // 返回13,Tab键占4
str.indexOf('233'); //返回-1,未找到

lastIndexOf(): Search for the last occurrence of the string position

var str = '赏花赏月赏秋香';
str.lastIndexOf('赏')//返回4,下标从左边0开始数起

includes():Search to determine whether the string contains the specified substring

var str = '哇拷I服了YOU';
str.includes('I')//true
str.includes('i')//区分大小写false
str.includes('I',3)//指定位置开始搜索,未找到返回false,

charAt(): Search returns the character at the specified position

var str = "做人如果没梦想,跟咸鱼有什么分别。";
str.charAt(5)//返回'梦'

++Interception and extraction
substring(): Returns a string in the specified index range
The string returned by substring() is the original one. Parameter one is the starting subscript (required, a non-negative integer); parameter two is the ending subscript (optional, a non-negative integer);

var s = '其实我是个演员';
s.substring(0, 2); // 从索引0开始到2(不包括2),返回'其实'
s.substring(5); // 从索引5开始到结束,返回'演员'
s.substring(5,7); // 下标超出后不报错,返回'演员'
s.substring(2, 0); // 反着写也可以,返回'其实'
s.substring(2, -1); // 下标为负数直接忽略为,返回'其实'
s.substring(-1, 2); // 下标为负数直接忽略为,返回'其实'

slice() : Extract a certain part of the string, and the returned string is new
The string returned by slice() is new. Parameter one is the starting index (required, a non-negative integer); parameter two is the ending index (optional, an integer, which can be negative).

var str='如花!真的是你!';
str.slice(0,3); //从索引0开始到2(不包括2),返回'如花!'
str.slice(3);// 从索引3开始到结束,返回'真的是你!'
str.slice(3,8);//下标超出后不报错,返回'真的是你!'
str.slice(3,0);//输出值为空
str.slice(3,-1);//负数下标从右边数起,返回'真的是你'
str.slice(-1,3);//输出值为空

substr() : Extract a string from the specified subscript to the specified number and length
substr() can pass two parameters. The first parameter is the starting subscript (if it is a negative number, then this parameter declares the position starting from the end of the string); the second parameter is the interception length (optional. In the substring number of characters, positive integer)

var str ='别以为你长得帅我就不打你';
str.substr(4,3)//从索引4开始取3位,返回'长得帅'
str.substr(-2)//负数下标从右边数起,返回'打你'
str.substr(-8,3)//,下标负时长度无效了,返回'长得帅我就不打你'
	
++Splicing
concat() : Extract a string from the specified subscript to the specified number and length

var str1 ='你可以叫我跑龙套的,'
var str2 ='但是请不要在前面加个“死”字好不好?'
var str3 ='哼,你个死跑龙套的。'
str1.concat(str2);//返回'你可以叫我跑龙套的,但是请不要在前面加个“死”字好不好?'
str1.concat(str2,str3);//返回'你可以叫我跑龙套的,但是请不要在前面加个“死”字好不好?哼,你个死跑龙套的。'

++replacement
replace() : Replace some characters with other characters or replace a substring that matches a regular expression.

var str = '我爱你!如果非要给这份爱加上一个期限,我希望是,一万年!'
str.replace('我爱你','我钟意你')
//返回"我钟意你!如果非要给这份爱加上一个期限,我希望是,一万年!"

str.replace('一','1')
//只匹配首个,返回"我爱你!如果非要给这份爱加上1个期限,我希望是,一万年!"

//正则表达
str.replace(/一/g,"1");
//"我爱你!如果非要给这份爱加上1个期限,我希望是,1万年!"

++Convert
toString() : Returns a value representing a String object.

//数字转换为字符串。
var num=727;
typeof(num) //"number"
num.toString()//"727"字符串
typeof(num.toString())//"string"

//数组转换成字符串
var fruits = ["Apple","Banana", "Mango","Orange"];
fruits.toString();//返回字符串"Apple,Banana,Mango,Orange"

   //进制转换
var num = 10; //默认10进制数字
num.toString(10)//转换成十进制,返回字符串"10"
num.toString(2)//转换成而进制,返回字符串"1010"
num.toString(8)//转换成八进制,返回字符串"12"
num.toString(16)//转换成十进制,返回字符串"a"
   //toString返回的是字符串,要转成数字用parseInt(num)

toUpperCase() : Convert the string to uppercase.

var str='WeianL';
str.toUpperCase()//返回'WEIANL'

toLowerCase() :Convert the string to lowercase.

var str='WeianL';
str.toLowerCase()//返回'weianl'

++Split into arrays
split(): Split a string into a string array

//直接分割
var str = '我左青龙,右白虎,老牛在腰间,龙头在胸口,人挡杀人,佛挡杀佛!'
str.split('')
/*
**  返回
**	["我", "左", "青", "龙", ",", "右", "白", "虎", ","
**	,"老", "牛", "在", "腰", "间", ",", "龙", "头", "在", "胸", "口", ","
**	,"人", "挡", "杀", "人", ",", "佛", "挡", "杀", "佛", "!"]
*/
//以逗号分割
str.split(',')//返回["我左青龙", "右白虎", "老牛在腰间", "龙头在胸口", "人挡杀人", "佛挡杀佛!"]

//第二个参数为返回的长度
str.split(',',2)//返回["我左青龙", "右白虎"]

//以空格分割
var str = '我左青龙 右白虎 老牛在腰间 龙头在胸口 人挡杀人 佛挡杀佛!'
str.split(' ')//返回["我左青龙", "右白虎", "老牛在腰间", "龙头在胸口", "人挡杀人", "佛挡杀佛!"]

Need to see more?

++ Rookie tutorial string operation method collection address
++ w3school string operation method collection address

Array methods

indexOf(): Search for the position where the first array appears

var arr = ['不', '上', '班', '行', '不', '行'];
arr.indexOf('行') // 下标从0开始,返回数字3
arr.indexOf('行',3) // 指定下标从3开始,算上3,返回数字3
arr.indexOf('行',4) // 指定下标从4开始,算上4,返回数字5
arr.indexOf('啊') // 搜索不到时,返回数字-1

lastIndexOf() : Search for the last array position that appears

var arr = ['不上班', '你养你', '啊', '?', '我养你', '啊','!'];
arr.lastIndexOf('啊') // 下标从0开始,返回数字5
arr.lastIndexOf('!') // 搜索不到时,返回数字-1

findIndex() : Returns the array element index that meets the conditions passed into the test (function).

var fruit = [
    { id: 1, name: 'apple' },
    { id: 2, name: 'orange' },
    { id: 3, name: 'grape' }
];
//find返回一整项,findIndex返回下标
var item = fruit.find(element => element.name == 'orange');
console.log(item); // { id: 2, name: 'orange' }

//根据对象某属性获得其在数组中的index
var index = fruit.findIndex(function(e) {
    return e.name == 'orange';
});
console.log(index); // 1

//es6版
var index = fruit.findIndex(element => element.name == 'orange');
console.log(index); // 1

includes() : Determine whether an array contains a specified value.

var arr = ['apple', 'banana', 'cheery'];
 
arr.includes('apple'); 
// true
 
arr.includes('tomato'); 
// false

arr.includes('apple',1); //从下表1开始
// false

some() : Method used to detect whether the elements in the array meet the specified conditions (provided by the function)

var arr = [18, 19, 20];
arr.some((age)=>age==18); 
// true
 
arr.some((age)=>age<18); 
// false

every() : Method used to detect whether all elements of the array meet the specified conditions

var arr = [18, 18, 18];
arr.every((age)=>age==18); 
// true

var arr = [18, 18, 19];
arr.every((age)=>age<=18); 
// false

filter() : method creates a new array. The elements in the new array are checked for all elements in the specified array that meet the conditions.

var arr = [1,2,3,4,5];
arr.filter(item=>item>3)
// [4, 5]

slice() : Add or remove elements from the array.

The slice() method does not alter the original array. Parameter 1: Optional. If it is a negative number, it will be counted from the end of the array; parameter two: optional. The end index of the array fragment. If not specified, it will be extracted to the end. If it is a negative number, it is the element starting from the end of the array.

var arr = ['一万年太久', ',', '爱我', '就现在', '!'];
arr.slice(0, 4); // 从索引0开始到4(不包括4),返回["一万年太久", ",", "爱我", "就现在"]
arr.slice(2); // 返回["爱我", "就现在", "!"]
arr.slice(-2); // 从后面算起,返回空数组["就现在", "!"]
arr.slice(2,6); // 超出长度按数组长度算,返回["爱我", "就现在", "!"]
arr.slice(2,0); // 参数二为0时,返回空数组[]
arr.slice(2,-1); // 参数二为负数时结束从后面算起,返回["爱我", "就现在"]
arr.slice(-2,1); // 返回空数组[]
	

splice() : Add or delete elements in the array (modify the "universal method" of Array).

splice() can pass 3 parameters. Parameter one: required. Specifies where to add/remove elements; parameter two: optional. Specifies how many elements should be deleted; parameter three: optional. new element to add to array

var arr = ['小强', ',', '小强', '你怎么了','小强'];

// 只删除,不添加:
arr.splice(2, 2); // ["小强", "你怎么了"]

// 只添加,不删除:
arr.splice(5, 0, '!', '!'); // 返回[],因为没有删除任何元素
arr; // 原有数组已改变为["小强", ",", "小强", "你怎么了", "小强", "!", "!"]

// 从索引2开始删除3个元素,然后再添加一个元素:
arr.splice(1, 3, '啊'); // 返回删除了的元素[",", "小强", "你怎么了"]
arr; // 原有数组变为["小强", "啊", "小强"]

unshift()和push(): Add one element to the beginning of the array, add one or more elements to the end of the array

//头部添加
var arr =['需要吗?','不需要吗?','需要吗?'];
arr.unshift('喜爱一个人需要理由吗?') // 返回长度5
arr; // ["喜爱一个人需要理由吗", "?", "需要吗?", "不需要吗?", "需要吗?"]

//尾部添加
var arr =['喜爱一个人需要理由吗?','需要吗?','不需要吗?'];
arr.push('需要吗','?') // 返回长度5
arr; // ["喜爱一个人需要理由吗?", "需要吗?", "不需要吗?", "需要吗", "?"]

shift()和pop(): Delete one element to the beginning of the array, delete one or more elements to the end of the array

//头部删除
var arr =['你会爱上一个你讨厌的人吗?','会吗?','不会吗?'];
arr.shift(); // 返回已删除元素"你会爱上一个你讨厌的人吗?"
arr; // ["会吗?", "不会吗?"]
arr.shift();arr.shift();arr.shift(); // 数组空时shift不会报错,而是返回undefined
arr; // 返回[]

//尾部删除
var arr =['你会爱上一个你讨厌的人吗?','会吗?','不会吗?'];
arr.pop(); // 返回已删除元素"不会吗?"
arr; // ["你会爱上一个你讨厌的人吗?", "会吗?"]
arr.pop();arr.pop();arr.pop(); // 数组空时pop不会报错,而是返回undefined
arr; // 返回[]
concat() : Concatenate two or more arrays
Please note that the concat() method does not modify the current Array, but returns a new Array
var arr1 = ['只要你说我行,'];
var arr2 = ['就算全天下的人都说我不行,'];
var arr3 = ['我也不在乎。'];
arr1.concat(arr2,arr3) // ["只要你说我行,", "就算全天下的人都说我不行,", "我也不在乎。"]
arr1; // ["只要你说我行,"]

 toString() : Convert array to string without specified separator

If the elements are not separated by a specified delimiter, the returned string will be separated by commas.

var arr = ['那个人样子好怪','我也看到了','他好像一条狗']
arr.toString() // "那个人样子好怪,我也看到了,他好像一条狗"

join() : Convert array to string with specified delimiter

Elements are separated by the specified delimiter.

var arr = ['面子不是别人给的','是自己凑上来丢的']
arr.join() // 什么都不传默认用逗号分隔,返回"面子不是别人给的,是自己凑上来丢的"
arr.join('') // "面子不是别人给的是自己凑上来丢的"
arr.join('——') // "面子不是别人给的——是自己凑上来丢的"

reverse() Reverse the order of elements in an array

var arr = ['我','吻','你','准','不'];
arr.reverse() // ["不", "准", "你", "吻", "我"]
sort() Sort the elements of an array

+++Array sorting

/***************排序数字****************/
var arr = [1, 100, 30, 20, 50, 40]
arr.sort() // 只能排序0-9以内的数组 结果[1, 100, 20, 30, 40, 50]
//所以需要封装一下
arr.sort(function(a,b){return a-b}); // [1, 20, 30, 40, 50, 100]
//写成ES6版
arr.sort((a, b) => a - b) //降序改为b-a
console.log(arr) // [1, 20, 30, 40, 50, 100]

//挂载到原型链的调用方式
Array.prototype.MySort = function() {
	return this.sort((a, b) => a - b)
}
var arr = [1, 100, 30, 20, 50, 40]
arr.MySort() // 调用
console.log(arr) // [1, 20, 30, 40, 50, 100]

/***************排序英文**************/
var arr= ["apple", "banana", "cat", "dog"];
arr.sort(); // ["apple", "banana", "cat", "dog"]

+++Object type array sorting


//对象数组排序
var arr = [
  	{num:27,barrage:'第一'},
    {num:0,barrage:'发条弹幕压压惊Σ(っ°Д°;)っ'},
    {num:17,barrage:'(ノ°ο°)ノ前方高能预警'},
    {num:7,barrage:'红红火火恍恍惚惚'}
];
 
function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;//降序为value2 - value1
    }
}
arr.sort(compare('num'))
/*
** 此时的arr为:
** [{num: 0, barrage: "发条弹幕压压惊Σ(っ°Д°;)っ"},
** {num: 7, barrage: "红红火火恍恍惚惚"},
** {num: 17, barrage: "(ノ°ο°)ノ前方高能预警"},
** {num: 27, barrage: "第一"}
*/ 
	

forEach() : Loop traversal without return
grammar array.forEach(function(currentValue, index, arr), thisValue)
currentValue Required. current element
index Optional. The index value of the current element.
arr Optional. The array object to which the current element belongs.
thisValue Optional. The object is used as the execution callback, passed to the function, and used as the value of "this". If thisValue is omitted, or null or undefined is passed in, then the this of the callback function is the global object.

var arr = ['前面漆黑一片','什么也看不到','也不是',' 天亮后会很美的']
var str = new String;
   arr.forEach((e,index)=>{
    str += `<div id='${index}'>${e}</div>`
})
str;
/*
** 此时的str为:
** "<div id='0'>前面漆黑一片</div>
** <div id='1'>什么也看不到</div> 
** <div id='2'>也不是</div>
** <div id='3'> 天亮后会很美的</div>"
*/
	
map() : Loop traversal with return
grammar array.map(function(currentValue,index,arr), thisValue)
currentValue Required. current element
index Optional. The index value of the current element.
arr Optional. The array object to which the current element belongs.
thisValue Optional. The object is used as the execution callback, passed to the function, and used as the value of "this". If thisValue is omitted, or null or undefined is passed in, then the this of the callback function is the global object.

var arr = ['我那么喜欢你','你喜欢我一下会死啊?']
var str = new String;
   str += arr.map((e,index)=>{
    return `<div id='${index}'>${e}</div>`
})
str;
/*
** 此时的str为:
** "<div id='0'>我那么喜欢你</div>,
** <div id='1'>你喜欢我一下会死啊?</div>"
** 细心的同学应该会发现返回的盒子与盒子之间是有逗号分隔的
*/

//此时我们可以用join()来处理掉逗号
var arr = ['我那么喜欢你','你喜欢我一下会死啊?']
var str = new String;
   str += arr.map((e,index)=>{
    return `<div id='${index}'>${e}</div>`
}).join('')
str;
/*
** 此时的str为:
** "<div id='0'>我那么喜欢你</div>
** <div id='1'>你喜欢我一下会死啊?</div>"
*/
	

After the data traversal of these two js arrays, it is not difficult to see that forEach() and map():
forEach() has no return value, while map() returns parameters through return,
and the value returned by map() will be in the form of commas. connected.

reduce() : Calculate array elements into a value (from left to right) reduce

reduce is very useful when finding the sum of an array or the sum of a certain value in an array object, so let’s talk about it

// 求数组的和
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function(prev, cur, index, arr) {
    // console.log(prev, cur, index);
    return prev + cur;
})
console.log(sum); // 10

// 简写
var arr = [1, 2, 3, 4];
var sum = arr.reduce((prev, cur)=>prev + cur)
console.log(sum); // 10

/****************************************************/

// 求数组对象某值的和
var arr = [{num: 1}, {num: 2}, {num: 3}, {num: 4}];
var sum = arr.reduce(function(prev, cur, index, arr) {
    // console.log(prev, cur, index);
    return prev + cur.num;
}, 0); // 第二个参数可以指定初始值
console.log(sum);// 10

// 简写
var arr = [{num: 1}, {num: 2}, {num: 3}, {num: 4}];
var sum = arr.reduce((prev, cur) => prev + cur.num, 0);
console.log(sum);// 10
More
++ Rookie tutorial array operation method collection address
++ w3school array operation method collection address

Guess you like

Origin blog.csdn.net/qq_43319351/article/details/131502196