在 JavaScript 中从特定位置替换数组值

javascriptweb developmentobject oriented programming更新于 2025/11/17 13:00:17

要从特定位置替换值,请在 JavaScript 中使用 splice()。以下是代码 −

示例

var changePosition = 2
var listOfNames = ['John', 'David', 'Mike', 'Sam','Carol']
console.log("Before replacing=");
console.log(listOfNames);
var name = 'Adam'
var result = listOfNames.splice(changePosition, 1, name)
console.log("After replacing=");
console.log(listOfNames)

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

node fileName.js.

输出

此处,我的文件名为 demo14.js。这将产生以下输出 −

PS C:\Users\Amit\JavaScript-code> node demo154.js
Before replacing=
[ 'John', 'David', 'Mike', 'Sam', 'Carol' ]
After replacing=
[ 'John', 'David', 'Adam', 'Sam', 'Carol' ]

相关文章


有用资源