var listOfUsers = ['Jon', 'Kevin', 'Sam', 'Lapito', 'Marshal'];
console.log(listOfUsers.splice(2, 1, 'Rachel')); // [ 'Sam' ]
为什么不打印呢,//["乔恩"、"凯文"、"瑞秋"、"拉皮托"、"元帅"]
为什么不打印,//['Jon','Kevin','Rachel','Lapito','Marshal']
因为这不是splice
返回的内容(MDN文档中的更多信息(。splice
返回通过调用移除的元素的数组。它会在适当的位置修改数组。
这可能有助于澄清:
const listOfUsers = ['Jon', 'Kevin', 'Sam', 'Lapito', 'Marshal'];
const returnValue = listOfUsers.splice(2, 1, 'Rachel');
console.log("updated listOfUsers:", listOfUsers);
console.log("return value of splice:", returnValue);
.as-console-wrapper {
max-height: 100% !important;
}
旁注:如果你只是用splice(2, 1, 'Rachel')
替换数组中单个元素的值,只需使用直接赋值:
listOfUsers[2] = "Rachel";
拼接是在数组上执行的,因此listOfUsers
将删除项,但方法本身会返回删除的项。
请参阅Array.prototype.splice((的MDN文档。