gpt4 book ai didi

javascript - undefined 被输出而不是对象属性

转载 作者:行者123 更新时间:2023-11-30 07:58:03 25 4
gpt4 key购买 nike

为什么输出 undefined 而不是对象属性。

创建了一个函数,为参数定义了setter,并输出由参数组成的字符串。

下面是 app.js 文件的片段。

// app.js

function Fruit(theColor, sweetness, theName, theOrigin) {

//properties
this.theColor = theColor;
this.sweetness = sweetness;
this.theName = theName;
this.theOrigin = theOrigin;

//functions
this.showName = function () {
console.log("This is a " + this.theName);
};

this.showLand = function () {
this.theOrigin.forEach(function (arg) {
console.log("Grown in: " + arg);
});
};
}

var mango = new Fruit("Yellow", 9, "Mango", ["India", "Central America"]);

console.log(mango.showName() + " " + mango.showLand());

最佳答案

这一行:

console.log(mango.showName() + " " + mango.showLand());

调用这些函数,然后输出它们的返回值,它们之间有一个空格。 showNamesshowLand 都不会返回任何内容,因此调用它们会得到结果 undefined

如果您只想调用那些,只需调用它们,而不使用console.log 输出它们的结果。例如,替换:

console.log(mango.showName() + " " + mango.showLand());

mango.showName();
mango.showLand();

如果您希望它们返回,而不是显示它们的结果,请编辑它们以实现此目的。您必须决定希望 showLand 如何分隔行(例如,使用 \n 或返回数组等)。

例如,showName 将返回一个字符串,showLand 将返回一个数组:

//functions
this.showName = function () {
return "This is a " + this.theName;
};

this.showLand = function () {
return this.theOrigin.map(function (arg) {
return "Grown in: " + arg;
});
};

然后你可以这样调用:

console.log(mango.showName() + ". " + mango.showLand().join(", "));

实例:

function Fruit(theColor, sweetness, theName, theOrigin) {

//properties
this.theColor = theColor;
this.sweetness = sweetness;
this.theName = theName;
this.theOrigin = theOrigin;

//functions
this.showName = function () {
return "This is a " + this.theName;
};

this.showLand = function () {
return this.theOrigin.map(function (arg) {
return "Grown in: " + arg;
});
};
}

var mango = new Fruit("Yellow", 9, "Mango", ["India", "Central America"]);

console.log(mango.showName() + ". " + mango.showLand().join(", "));

关于javascript - undefined 被输出而不是对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35068590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com