gpt4 book ai didi

javascript - 如果数组长度大于1则执行

转载 作者:行者123 更新时间:2023-12-03 04:56:39 31 4
gpt4 key购买 nike

如果数组的长度大于 1,那么我希望控制台记录所需的代码,但控制台会记录 else 语句。

var hello = "Hello, ";
var arrayNames = [];

function greet(name){

if(name==null){
console.log(hello + "my friend")
}

//Requirement UpperCase
for (var i = 0; i < name.length; i++) {
if(name[i]===name[i].toUpperCase()){
console.log(hello.toUpperCase() + name[i].toUpperCase())

}

}
//Requirement last element
arrayNames.push(name)

if(arrayNames.length>1){

var lastElement = arrayNames.pop()
console.log(hello + arrayNames + " and " + lastElement)
}


else{
console.log(hello + arrayNames)
}


}

greet(["James", "Garry", "JOSHUA", "steven"])

最佳答案

您正在将整个数组作为元素推送到另一个数组中。

//Requirement last element
arrayNames.push(name) //[Array[4]]

//change this to
Array.prototype.push.apply(arrayNames, name)

// if you want to use spread operator do this
arrayNames.push(...name)

关于javascript - 如果数组长度大于1则执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42406626/

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