有人可以解释这个功能吗?

时间:2014-01-01 21:07:42

标签: javascript function parameters

function doesOwnSet(player, type) {
// we'll use "chaining" here, so every next method will be called upon
// what previous method have returned

// `return` statement will return the result of the very last method

// first, lets take an array of `position` object keys
// which are "position1", "position2" and so on
return Object.keys(positions)

    // then, create an array of positions object
    // this will return Array
    .map(function (key) {
        return positions[key];
    })

    // then, pick up only positions with specified type (aka set)
    // this will return Array
    .filter(function (pos) {
        return pos.type === type;
    })

    // finally, check if specified player owns every position of the set
    // this will return Boolean
    .every(function (pos) {
        return pos.owner === player;
    });
}

我不明白“key”和“pos”这两个词的来源。这些是功能的名称吗?尽管有评论,我真的不明白。这是question的答案。代码有效,但我不明白它的作用。

1 个答案:

答案 0 :(得分:2)

Object.keys返回对象“自己”键的数组。

.map().filter().every()迭代数组,一次将每个值传递给回调,因此key中的.map()为当前迭代的对象键。

无论.map()回调返回是作为返回的新数组的成员添加的,因此.filter().every()对新的数组值进行操作。

.filter()将创建回调返回true(或任何真值)的值的数组。

.every()如果其回调为每次迭代返回一个truthy值,则返回true,否则返回false

在回调中调用console.log()以查看值的含义。

function doesOwnSet(player, type) {
// we'll use "chaining" here, so every next method will be called upon
// what previous method have returned

// `return` statement will return the result of the very last method

// first, lets take an array of `position` object keys
// which are "position1", "position2" and so on
return Object.keys(positions)

    // then, create an array of positions object
    // this will return Array
    .map(function (key) {
        console.log(key);
        return positions[key];
    })

    // then, pick up only positions with specified type (aka set)
    // this will return Array
    .filter(function (pos) {
        console.log(pos);
        return pos.type === type;
    })

    // finally, check if specified player owns every position of the set
    // this will return Boolean
    .every(function (pos) {
        console.log(pos);
        return pos.owner === player;
    });
}