Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript中易混淆的split、splice、slice方法 #37

Open
zlluGitHub opened this issue Oct 22, 2018 · 0 comments
Open

JavaScript中易混淆的split、splice、slice方法 #37

zlluGitHub opened this issue Oct 22, 2018 · 0 comments

Comments

@zlluGitHub
Copy link
Owner

Split

Split 是切割字符串的一种方法,该方法主要用于把一个字符串分割成字符串数组。
注意:字符串是不可变的,因此本方法是产生新的字符串数组。

var str = "How do you do";
var arr = str.split(" "); // 使用 " " 空格来切割字符串
console.log(arr.length) //输出 4
console.log(arr) //输出 ["How","do","you","do"]

Splice

splice()方法向是从数组中添加或删除或替换元素,然后返回被删除的元素组成的数组。

删除:array.splice(index,num),返回值为删除内容,array为结果值。index为起始项,num为删除元素的的个数。
var array = ["a","b","c","d"]; 
var removeArray = array.splice(0,2); 
console.log(array);//输出 ["c","d"] 
console.log(removeArray);//返回值为删除项,即输出 ["a","b"]
插入:array.splice(index,0,insertValue),index要插入的位置,insertValue要插入的项 。
var array = ["a","b,"c","d"]; 
var removeArray = array.splice(1,0,"insert"); 
console.log(array); //输出 ["a","insert","b","c","d"]
console.log(removeArray); //输出 空
替换:array.splice(index,num,insertValue),index起始位置,num要被替换的项数,insertValue要替换的值
var array = ["a","b","c","d"]; 
var removeArray = array.splice(1,1,"insert"); 
console.log(array); //输出 ["a","insert","c","d"] 
console.log(removeArray); //输出 ["b"]

Slice

slice()方法主要用于截取数组,并返回截取到的新数组。
注意:该方法是返回的一个新的数组,原数组没有做任何改变。

var arr1 = ["a", "b", "c", "d", "e", "f"];
    // 从下标为0的位置开始截取,截取到下标2,但是不包括下标为2的元素. 原数组没有任何的变化
    var newArr = arr1.slice(0, 2);
    console.log(newArr); //输出 ["a", "b"]
    console.log(arr1.slice(2));  //输出 ["c", "d", "e", "f"]
    //从倒数第5个元素,截取到倒数第2个
    console.log(arr1.slice(-5, -2)); //输出 ["b", "c", "d"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant