我創建了一個change可用于更改name物件的函式person。
該函式有一個引數,該引數將是物件的新名稱。
但是我傳遞給這個引數的新名字變成...is not defined了,我在這里錯過了什么?
Edited
thisIsNewName是一個字串,這是替換Ali.
因此,要修改物件文字的屬性,我們使用點語法或方括號,而修改屬性的常規Ali方式person是person.name = 'newName'. 但是我的代碼中有很多person,我想使用一個函式來做到這一點。
const person = {
name: 'Ali',
Age: '18'
}
function change(text) {
person.name = text;
}
change('thisIsNewName');
console.log(person.name);
uj5u.com熱心網友回復:
您正在嘗試傳遞您未定義的引數。您可以創建變數,也可以直接將字串傳遞給它
const person = {
name: 'Ali',
Age: '18'
}
function change(text) {
person.name = text;
}
let thisIsNewName = 'ALI2';
change(thisIsNewName);
//Or you can pass directly string
//change("thisIsNewName");
console.log(person.name);
uj5u.com熱心網友回復:
thisIsNewName是一個字串,這是替換阿里。
不,這不對。
thisIsNewName未在您的代碼中定義。
定義變數并分配一個字串
const person = {
name: 'Ali',
Age: '18'
}
function change(text) {
person.name = text;
}
const thisIsNewName = 'newName';
change(thisIsNewName);
console.log(person.name);
或使用字串文字呼叫函式
const person = {
name: 'Ali',
Age: '18'
}
function change(text) {
person.name = text;
}
change('thisIsNewName');
console.log(person.name);
uj5u.com熱心網友回復:
如果您的意思是這樣,您應該將名稱作為字串傳遞 ->change("thisIsNewName")
但是如果您想將變數傳遞給函式,請在使用之前定義它:let thisIsNewName = "new name"
const person = {
name: 'Ali',
Age: '18'
}
function change(text) {
person.name = text;
}
change("thisIsNewName"); //*
console.log(person.name);
或者
const person = {
name: 'Ali',
Age: '18'
}
function change(text) {
person.name = text;
}
let thisIsNewName = "new name";//*
change(thisIsNewName);
console.log(person.name);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/463197.html
標籤:javascript
