JS shift & unshift


shift() method deletes the first element of an array, returns the deleted first element:

var arr = new Array(1,2,3,4,5);
var ret = arr.shift(); //delete 1, arr now is [2,3,4,5]
console.log(ret);  //1

To shift a letter from string:

var str = "12345";
var str = str.substr(1);
console.log(str);   //str = "2345"

unshift() method adds 1 element to the array start position, return the new array length:

var arr = new Array(1,2,3,4,5);
var ret = arr.unshift(10); //arr now is [10,1,2,3,4,5]
console.log(ret); //6

endmemo.com © 2024  | Terms of Use | Privacy | Home