2016-12-15 58 views
-2

我在輸入數組時遇到了問題,嘗試在CodeWars上使用Javascript挑戰。SyntaxError:意外的標記[,var name [] array

這裏是指令:實現一個函數likes :: [String] - > String,它必須包含輸入數組,其中包含喜歡項目的人的姓名。它必須返回如例子中的顯示文本:

likes [] // must be "no one likes this" 
likes ["Peter"] // must be "Peter likes this" 
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this" 
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this" 
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this" 

Basicliy它像系統一樣了Facebook。有人能解釋我做錯了什麼嗎?這裏是我的審判代碼

function likes (names) { 
    var names[7]; 
    if (names.length=0) { 
     return "nobody likes this" 
    } else if (names.length=1) { 
     return names[0]+"likes this"; 
    } else if (names.length=2) { 
     return names[0]+names[1]"like this" 
    } else if (names.length=3) { 
     return names[0]+''+names [1]+''+names[2]+''+ " likes this" 
    } else (names.length >3) { 
     return names[0]+''+names [1]+''+ names.length-1 + "likes this" 
    } 
} 
+0

函數調用應該是'喜歡()''不喜歡[]' –

回答

0

var names是聲明瞭一個名爲names變量的語法。

names[7]是讀取names的值的語法,然後訪問名爲7的結果對象上的屬性。

您不能創建變量並同時訪問其值的屬性......該變量的值尚未分配。

0

試試這個代碼,而不是你的代碼,簡單的概念

var likes=[]; 

//call this like function with name as parameter, while click the like button 
function like(name) 
{ 
likes.push(name); 
} 

function viewlikes(){// here you need write the condition and call where you want display the details   
    if(likes.length==0) 
    { 
    return " nobody likes this" 
    } 

if(likes.length==1) 
    { 
    return likes[0] + " like this" 
    } 

if(likes.length==2) 
    { 
    return likes[0] + "," + likes[1] + " like this"  
    } 
if(likes.length==3) 
    { 
    return likes[0] + "," + likes[1] + " and " + likes[2] + " like this"  
    } 
    return likes[0] + "," + likes[1] + " and " + likes.length-2 " others like this" 
    } 
相關問題