要从特定位置替换值,请splice()在JavaScript中使用。以下是代码-
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' ]