2017-03-23 1 views
1

다음 코드는 Mike Bostock의 Force-Directed Graph with Mouseover에서 가져온 것입니다. 나는이 코드에 대해 좀 더 지적한 질문을 할 수 없다는 점을 유감스럽게 생각하지만 누군가가 링크에서 다른 노드를 계산하는 forEach 블록의 구문을 설명 할 수 있는지 궁금합니다.JavaScript의 다중 할당 표현식 및 구문 설명

아래 줄에서 정확히 무슨 일이 일어나고 있으며 어떤 변수에 할당되고 있습니까? 동일한 표현식에 여러 개의 과제를 수행 할 수있는 이름이 있습니까?

link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});

var links = [ 
    {source: "Ericsson", target: "ZTE", type: "suit"}, 
    {source: "Kodak", target: "Samsung", type: "resolved"}, 
    {source: "Apple", target: "Samsung", type: "suit"}, 
    {source: "Kodak", target: "RIM", type: "suit"}, 
    {source: "Nokia", target: "Qualcomm", type: "suit"} 
]; 

var nodes = {}; 

// Compute the distinct nodes from the links. 
links.forEach(function(link) { 
    link.source = nodes[link.source] || (nodes[link.source] = {name: link.source}); 
    link.target = nodes[link.target] || (nodes[link.target] = {name: link.target}); 
}); 

답변

2

이 줄을 풀고 공정한 금액 실제로있다 : x = y || z이에 * 같다고

link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});

먼저이 언급되어야한다

if (y) 
    x = y; 
else 
    x = z; 

It i = (j = k)kj에 할당하고이 값을 i에도 할당한다는 의미입니다. 따라서 결국 i, jk은 모두 동일한 값을 갖게됩니다. nodes[link.source]가 (0이 아닌, 널 (null), 정의되지 않은, 빈 문자열) truthy 경우입니다

if (nodes[link.source]) { 
    link.source = nodes[link.source]; 
} else { 
    nodes[link.source] = { name: link.source }; 
    link.source = nodes[link.source]; 
} 

, 다음 link.source이 nodes[link.source] 할당됩니다 :이 경우에 따라서

, 우리는 정말이가 있어요 값으로.

위변조 인 경우 link.sourcenodes[link.source]에 해당 값이 {name: link.source}으로 지정됩니다. 당신이 ||을 평가할 때 왼쪽이 truthy 경우, 오른쪽을 평가할 필요가 없기 때문에


*이 사람들은 동일합니다 - 당신은 이미 참으로 문을 평가할 수 있습니다. 따라서 JavaScript에서는 y이 사실 일 경우 y을 반환하고 은 y은 거짓이지만 z은 사실이거나 false은 위증입니다.