gpt4 book ai didi

输出语句末尾的 Javascript 对象未定义关键字

转载 作者:行者123 更新时间:2023-11-30 10:18:13 24 4
gpt4 key购买 nike

我在 javascript 中创建了一个运行良好的对象,但在每个语句的末尾都显示“未定义”。这是我的 javascript。

<script>
window.onload=function(){
function sports(sportsname, country, player, difficulty){
this.sportsname = sportsname;
this.country = country;
this.player = player;
this.difficulty = difficulty;
this.hissportstaste = sportstaste;
}

var Cricket = new sports("Cricket", "Pakistan", "Shahid Afridi", "Difficult");
var Football = new sports("Football", "Spain", "David Villa", "Difficult");
var Tennis = new sports("Tennis", "Switzerland", "Roger Federer", "Difficult");

function sportstaste(){
if(this.country == "Pakistan"){
document.write(this.player + " Is the best and he is a " + this.sportsname + " Player");
}
if(this.country == "Spain"){
document.write(this.player + " Is the best and he is a " + this.sportsname + " Player");
}
if(this.country == "Switzerland"){
document.write(this.player + " Is the best and he is a " + this.sportsname + " Player");
}
}
document.write(Cricket.hissportstaste());
document.write("<br>");
document.write(Football.hissportstaste());
document.write("<br>");
document.write(Tennis.hissportstaste());
document.write("<br>");
}

</script>

及其给出的输出是。

Shahid Afridi Is the best and he is a Cricket Playerundefined
David Villa Is the best and he is a Football Playerundefined
Roger Federer Is the best and he is a Tennis Playerundefined

我期待这个输出。

Shahid Afridi Is the best and he is a Cricket Player
David Villa Is the best and he is a Football Player
Roger Federer Is the best and he is a Tennis Player

有什么想法吗??

最佳答案

改变

document.write(Football.hissportstaste());

Football.hissportstaste();

对于类似的调用也是如此:您的函数不返回任何内容(undefined)并且已经写入文档。

但是你应该尽量避免document.write,这个函数有非常特殊的用途(it can't be used once the document is loaded),你应该学会改变DOM(参见this例如)。

关于输出语句末尾的 Javascript 对象未定义关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22683788/

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