简体   繁体   English

试图在javascript中理解.some()

[英]Trying to understand .some() in javascript

This is a portion of code from https://bl.ocks.org/mbostock/4183330 这是来自https://bl.ocks.org/mbostock/4183330的代码的一部分

I am trying to understand how names.some(function(d)...}) works. 我试图理解names.some(function(d)...})工作原理。

  1. Shouldn't the anonymous function passed to .some() return a conditional statement that "countires" can be evaluated against? 不应该传递给.some()的匿名函数返回一个条件语句,可以对“countires”进行评估吗?

  2. When will names.some(..) return true or false? names.some(..)何时返回true或false?

  3. Why doesn't d.name = n.name create "name" property in "countries" without "return"? 为什么d.name = n.name在没有“return”的情况下在“countries”中创建“name”属性?

queue()
    .defer(d3.json, "world-110m.json")
    .defer(d3.tsv, "world-country-names.tsv")
    .await(ready);

function ready(error, world, names) {
    var countries = topojson.feature(world,world.objects.countries).features
    countries = countries.filter(function(d) {
        return names.some(function(n) {
                  if (d.id == n.id) return d.name = n.name;
     });
})

1) Since it's using names.some() , the function is testing each element of names , not countries . 1)由于它使用names.some() ,该函数正在测试names每个元素,而不是countries

2) When any of the names have an id that matches d.id and n.name is not empty. 2)当任何名称的idd.id匹配且n.name不为空时。

3) It will always create the property. 3)它将始终创建属性。 But if there's no return , .some() doesn't get a truth value that it can evaluate. 但如果没有return.some()不会得到它可以评估的真值。

It would probably be easier to understand if they'd written: 如果他们写的话可能会更容易理解:

return names.some(function(n) {
    if (d.id == n.id) {
        d.name = n.name;
        return d.name;
    } else {
        return false;
    }
});

return d.name = n.name; combines the assignment and return value into a single statement. 将赋值和返回值组合到一个语句中。 And the code is making use of the fact that functions implicitly return undefined when they don't execute a return statement, and undefined is falsey. 并且代码正在利用这样的事实:当函数不执行return语句时,函数隐式返回undefined ,而undefined是falsey。

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

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