为此创建一个函数

时间:2015-11-18 02:09:10

标签: javascript function

        /* global nonFriends */
        QUnit.test("nonFriends() : Should take a name and a list of people, and return a list of all the names that <name> is not friends with", function(assert){
            var data = [
                {name: "Jimmy", friends:["Sara", "Liza"]},
                {name: "Bob", friends:[]},
                {name: "Liza", friends: ["Jimmy"]},
                {name: "Sara", friends: ["Jimmy"]}
            ];
            assert.deepEqual(nonFriends("Jimmy", data), ["Bob"]);
            assert.deepEqual(nonFriends("Bob", data), ["Jimmy", "Liza", "Sara"]);
            assert.deepEqual(nonFriends("Sara", data), ["Bob","Liza"]);
        });

无法解决这个问题。我需要创建一个函数来获取一个名字和一个人的列表,并返回一个不是朋友的所有名字的列表。但是无法循环数据

1 个答案:

答案 0 :(得分:1)

试试这个:

var nonFriends = function (name, list) {
    var nonfriends = []; // this will be the list we return
    for (var i = 0; i < list.length; i++) { //iterate over the parameter
        var friends = list[i].friends; 
        var isFriend = false;
        if (list[i].name !== name) { //if this isn't the person we're testing for
            for (var e=0; e < friends.length; e++) { //iterate over their friends
                if (friends[e] === name) { //if they have the person as a friend
                    isFriend = true; //record that they have the person as a friend
                } 
            }
            if (!isFriend) nonfriends.push(list[i].name); //after iterating over all their friends, if they didn't have the person as a friend, add them to the list to be returned
        } else {
            isFriend = true; //this else clause isn't doing anything, I just wrote it in hastily and superfluously when I added the logic that a person is a friend of herself.
        }
    }
    return nonfriends;
};