在 JavaScript 中创建新数组而不影响旧数组的值?

javascriptweb developmentobject oriented programming更新于 2025/11/14 0:44:17

假设以下是我们当前的数组减去

var listOfNames=["John","Mike","Sam","Carol"];

使用 JSON.parse(JSON.stringify()) 创建新数组并从上面的旧数组设置值。

示例

function createNewArray(listOfNames) {
   return JSON.parse(JSON.stringify(listOfNames));
}
var listOfNames=["John","Mike","Sam","Carol"];
var namesArray = listOfNames.slice();
console.log("The new Array=");
console.log(namesArray);

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo111.js。

输出

这将产生以下输出 −

PS C:\Users\Amit\JavaScript-code> node demo111.js
The new Array=
[ 'John', 'Mike', 'Sam', 'Carol' ]

相关文章


有用资源