简体   繁体   English

Javascript从索引处的数组获取值,同时如果索引不存在则避免未定义?

[英]Javascript get value from array at index while avoiding undefined if index does not exist?

Coming from Python, it is very odd for me to see this JavaScript: 来自Python,看到这个JavaScript对我来说很奇怪:

a = []
b = a[0] 
b === undefined // returns true

In Python a[0] would throw an index error, and would prevent you from continuing and potentially running into more errors in the future. 在Python中,a [0]会引发索引错误,并且会阻止您继续运行,并可能在将来遇到更多错误。 B would never be set to undefined. B永远不会设置为undefined。

In Python I could do something like: 在Python中,我可以执行以下操作:

a = [1, 2, 3]
try:
    b = a[5]
except IndexError:
    print('Index out of range')

b could never be set to undefined, which would prevent potential weird things happening later on. b永远不能设置为undefined,这将防止以后发生潜在的奇怪事件。 What is the best way for me to handle this in JavaScript? 我用JavaScript处理此问题的最佳方法是什么? I tend to want to try something like this: 我倾向于尝试这样的事情:

a = []
b = a[0] || <something other than undefined>

In the case that a is supposed to be a list of objects it could be: 在假设a是对象列表的情况下,它可能是:

a = []
b = a[0] || {} // set b to empty object instead of undefined

I think a common way of handling this in JavaScript is handling it further down the line: 我认为在JavaScript中处理此问题的常用方法是进一步处理该问题:

a = []
b = a[0]

if (b) {
    // do something if b is defined
}

// or 

if (!b) {
    // do something if b is undefined 
}

In JavaScript is there a best or common practice for avoiding setting something to undefined? 在JavaScript中,有没有避免将某些内容设置为undefined的最佳或通用做法? And in this specific case of accessing an array what is the best way to avoid setting something to undefined? 在这种访问数组的特定情况下,避免设置未定义内容的最佳方法是什么?

You could use in operator operator, which check if a property exists in an object/array with a conditional (ternary) operator ?: for either the value or some default value. 您可以in运算符 operator中使用它,该运算符使用条件(三元)运算符?:检查对象/数组中是否存在属性?:值或默认值。

This approach saves falsy values as well. 这种方法还可以保存虚假的值。

const b = 0 in aa ? a[0] : <something other than undefined>;

What you are seeing is basically a design decision. 您所看到的基本上是一个设计决策。 It's just how JavaScript works. 这就是JavaScript的工作方式。 For example PHP is similar in the sense that accessing a non existing index is a warning rather than a hard error. 例如,PHP在某种意义上类似,即访问不存在的索引是警告而不是硬错误。 There's probably other language examples out there that behave this way. 可能还有其他以这种方式表现的语言示例。

To get around this: 为了解决这个问题:

A common way is indeed using b = a[0] || "default" 确实,一种常见的方法是使用b = a[0] || "default" b = a[0] || "default" however beware of the behaviour with falsy but not undefined values as for example: 但是, b = a[0] || "default"当心带有虚假但不是未定义值的行为,例如:

 var myarray = [ 0, null, "" ]; var a = myarray[0] || "default[0]"; var b = myarray[1] || "default[1]"; var c = myarray[2] || "default[2]"; var d = myarray[3] || "default[3]"; console.log(a, b, c, d); 

If you want to strictly check for undefined while allowing falsy values to be used do be explicit: 如果要在允许使用假值的同时严格检查未定义内容,请明确说明:

  var myarray = [ 0, null, "" ]; var a = myarray[0] !== undefined ? myarray[0] : "default[0]"; var b = myarray[1] !== undefined ? myarray[1] : "default[1]"; var c = myarray[2] !== undefined ? myarray[2] : "default[2]"; var d = myarray[3] !== undefined ? myarray[3] : "default[3]"; console.log(a, b, c, d); 

The JavaScript Execution is little different from other programming languages. JavaScript执行与其他编程语言几乎没有什么不同。 JavaScript doesn't create intermediate code which languages like C, Java creates (eg- byte code). JavaScript不会创建由C,Java之类的语言创建的中间代码(例如,字节代码)。 The first phase in Javascript is the declaration phase where variables are defined in their respective scope. Javascript的第一阶段是声明阶段,在此阶段,变量在各自的范围内定义。 The default scope is the global scope. 默认范围是全局范围。 Each function creates its own scope in javascript. 每个函数在javascript中创建自己的范围。

var a = 10;

So in 1st phase it will define 'a' in global scope. 因此,在第一阶段 ,它将在全局范围内定义“ a”。 Note that its not initialising it with value 10. The next phase is the initialisation phase where the value of 10 is assigned to the var 'a'. 请注意,它不会使用值10对其进行初始化。 下一个阶段是初始化阶段,其中将值10分配给变量'a'。 if a is not declared any value it will be initialised as 'undefined' . 如果没有声明a的任何值,它将被初始化为'undefined'

In the end you have to remember that its just the way JavaScript does it. 最后,您必须记住,这只是JavaScript的方式。

In a future release of JavaScript (current date 7/16/18) nullish coalescing should be available: 在将来的JavaScript版本中(当前日期为7/16/18),可以使用无效合并:

Instead of: 代替:

value != null ? value : 'default value';

Or: 要么:

value || 'default value'

(The number zero, the boolean false, and an empty string are all considered false in the second solution. Very dangerous.) (在第二个解决方案中,数字零,布尔值false和空字符串都被视为false。非常危险。)

Now we can do: 现在我们可以做:

value ?? 'default value';

Docs: https://github.com/tc39/proposal-nullish-coalescing 文件: https//github.com/tc39/proposal-nullish-coalescing

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

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