Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - What is the exact meaning of this code using the || ("OR") operator?

I saw somewhere this code snippet:

var idx = SOME_VALUE;

var color = {
  yellor: 1,
  red: 2,
  black: 0
};

var x = color[idx] || []; // Is this means if color[idx] is null, then return an empty array?

I can only guess the code var x = color[idx] || []; means if color[idx] is null, then return an empty array to x otherwise x= color[idx]. Am I right?

Still, I need an explaination. Does this code has the same logic as the following?

CONDITION==VALUE? TRUE_goes_here : FALSE_goes_here
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What it means is that if color[idx] is "falsy," use an empty array instead. "Falsy" values are false (of course), 0, NaN, "", undefined, and null (all other values are "truthy"). That idiom is an example of JavaScript's curiously powerful || operator*.

In this case, it's supplying a default value if color doesn't contain a property with the name contained by idx (because when you index into an object like that and the key doesn't match any existing property name, the result is undefined): x will be 1 (if idx is "yellor"), 2 (if idx is "red"), 0 (if idx is "black"), or [] if idx is anything else.

So answering your question at the end of your question, basically, yes. It's:

var x = color[idx];
if (!x) {
    x = [];
}

or

var x = color[idx] ? color[idx] : [];

* (That's a post on my anemic little blog.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...