gpt4 book ai didi

javascript - 几个数组为空

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

我有 3 个数组:

tabNoms = new Array("Jean", "Maximilien", "Brigitte", "Sonia", "Jean-Pierre", "Sandra");
tabMaximum = new Array();
tabMinimum = new Array();

目标是从数组 tabNoms 中恢复每个元素,它必须有最多 4 个字母和 put in tabMaximum。

这是我的算法,但它不起作用

tabNoms = new Array("Jean", "Maximilien", "Brigitte", "Sonia", "Jean-Pierre", "Sandra");
tabMaximum = new Array();
tabMinimum = new Array();
function main()
{
for(var i = 0; i<tabNoms.length; i++){
if(tabNoms[i] < 4){
tabMaximum.push(tabNoms[i]);
}
}
document.write("Maximum 4 letters : " + tabMaximum);
}

你有想法吗?请 ?谢谢

最佳答案

你必须纠正你的if condition。改变

if(tabNoms[i] < 4){

为此

if(tabNoms[i].length <= 4){

因为这里你要检查stringlength

tabNoms = new Array("Jean", "Maximilien", "Brigitte", "Sonia", "Jean-Pierre", "Sandra");
tabMaximum = new Array();
tabMinimum = new Array();



function main()
{
for(var i = 0; i<tabNoms.length; i++){
if(tabNoms[i].length <= 4){
tabMaximum.push(tabNoms[i]);
}
}
console.log("Maximum 4 letters : " + tabMaximum);
}
main();

var result=tabNoms.filter(obj => obj.length <= 4);
console.log(result);

  1. 您也可以使用 Array.propotype.filter()

    var result=tabNoms.filter(obj => obj.length <= 4);
    console.log(result);

tabNoms = new Array("Jean", "Maximilien", "Brigitte", "Sonia", "Jean-Pierre", "Sandra");
var result = tabNoms.filter(obj => obj.length <= 4);
console.log(result);

关于javascript - 几个数组为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52468239/

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