我想编写一个程序来打印数组中的第三个项目 [英] I want to write a program that prints the third item in an array

查看:70
本文介绍了我想编写一个程序来打印数组中的第三个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是希望程序打印数组中的第3项(如果有的话),如果不存在我想要打印Null。



< b>我尝试过的事情:



I just want the program to print the 3rd item in an array if there is one and if there isnt i want it to print "Null".

What I have tried:

const names = ["charlie","ben","randy"];

if (names.length = 2){
console.log(names[2]);
}
else{
 null;
}

推荐答案

这里有几个问题。



1. Javascript使用 = 来分配值。

---等值比较是两个等号 = =

---三个等号 === 比较值和类型是否相等



2. else 只有空值。不会打印出来。

---替换为 console.log(null);



所以我最终得到了
A couple of problems here.

1. Javascript uses = to assign a value.
--- The equal value comparison is two equal signs ==
--- Three equal signs === compares value AND type for equality

2. The else only has null in it. Won't print it.
--- Replace with console.log("null");

So I ended up with
const names = ["charlie","ben","randy"];
  if (names.length == 2){
    console.log(names[2]);
  } else{
     console.log("null");
  }

嗯。它只是log null 。为什么是这样?所以我更新了 else

Hmmmm. All it does is log null. Why is this? So I updated the else block

else{
     console.log("null");       // what you want
     console.log(names.length); // for troubleshooting
 }

所以它仍然记录 null 现在它也记录3。

哦是的,而数组索引是基于0的;长度是另一个故事。

填充数组的长度为1。数组中的最后一个元素通常具有索引(length-1)。

空数组的长度为0,元素[0]为未定义



现在你可以做出决定;你想要这样吗,或者你想要 names.length == 3 ,或者大于比较 names.length> 2



在所有现实中,使用代码打开记事本等并打开一个浏览器应该不会太难保存的html文档。这就是我做的!

So it still logs the null and now it also logs "3".
Oh yeah, while the array indexes are 0 based; length is another story.
A populated array has a length that is 1-based. The last element in the array generally has an index of (length-1).
An empty array has a length of 0, and element[0] is undefined

So now you get to make a decision; do you want it this way, or do you want names.length==3, or how about a greater than comparison names.length > 2?

In all reality, it shouldn't be too hard to have notepad etc open with the code and a browser open to that saved html document. It's what I did!


引用:

我只想让程序打印出第3个项目如果有一个数组,如果有,我希望它打印Null。

I just want the program to print the 3rd item in an array if there is one and if there isnt i want it to print "Null".



要打印数组的第三个元素,其长度必须至少为3。

您使用 console.log 打印名称的第三个元素,您也必须将其用于null。


To print the third element of array, its length must be at least 3.
You are using console.log to print third element of names, you must use it for null too.

const names = ["charlie","ben","randy"];

if (names.length == 3){
    console.log(names[2]);
}
else{
    console.log("null");
}


这篇关于我想编写一个程序来打印数组中的第三个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆