繁体   English   中英

Javascript 无效 function? 我缺少什么?

[英]Javascript invalid function? what I am missing?

我使用 textwrangler 编写我的代码以更好地显示我的代码和进度。 在我的代码的评论部分,我写下了我的担忧和我的代码的目的。

var pets = ["pet1", "pet2", "pet3"]

function displayPets() {
    console.log("my pets:", pets);
}

// addPets() will name all new pets "new pets" ie ("pet1", "pet2", "pet3", "new pets"....)

function addPets() {
    pets.push("new pet");
    displayPets();
}

/ try different method using the parameter

function addPets(petName) {
    pets.push("petName");
    displayPets();
}

// pets.push isn't not a function
addPets(brutus)

将在不同的和第一个 function 中使用相同的名称,您可能会看到另一个错误(基本上不是错误,它只是一个错误),您不能从周边获取输入,这是因为您推送的是字符串而不是变量在不同的方法中,当您调用不同的 function 时,您没有输入也会导致错误的字符串,如果您不理解,希望下面的代码可以提供帮助

 var pets = ["pet1", "pet2", "pet3"] function displayPets() { console.log("my pets:", pets); } // addPets() will name all new pets "new pets" ie ("pet1", "pet2", "pet3", "new pets"....) function addPets() { pets.push("new pehttps://stackoverflow.com/questions/44062303/javascript-invalid-function-what-i-am-missing#t"); displayPets(); } // try different method using the parameter function addPetsDifferentMethod(petName) { pets.push(petName); displayPets(); } // pets.push isn't not a function addPetsDifferentMethod("brutes")

JS 中没有重载函数。 最后一个总是会被调用。 我们必须编写 function 定义来表现得像重载function。fiddle

 function addPets(petName){
       if(petName){ // if petname is present
        pets.push(petName)
      }
      else{
      pets.push("newPet");
      }
      displayPets();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM