Để thay thế giá trị từ vị trí cụ thể, hãy sử dụng splice() trong JavaScript. Dưới đây là mã:
Ví dụ
var changePosition = 2
var listOfNames = ['John', 'David', 'Mike', 'Sam', 'Carol']
console.log("Trước khi thay thế=");
console.log(listOfNames);
var name = 'Adam'
var result = listOfNames.splice(changePosition, 1, name)
console.log("Sau khi thay thế=");
console.log(listOfNames)
Để chạy chương trình trên, bạn cần sử dụng lệnh sau:
node fileName.js
Kết quả
Tên tệp của tôi là demo14.js. Chương trình sẽ cho ra kết quả sau:
PS C:\Users\Amit\JavaScript-code> node demo154.js Trước khi thay thế= [ 'John', 'David', 'Mike', 'Sam', 'Carol' ] Sau khi thay thế= [ 'John', 'David', 'Adam', 'Sam', 'Carol' ]