显示在浏览器中不起作用的对象数组

时间:2018-05-06 19:24:23

标签: javascript arrays object

我想创建一个对象数组,并在满足某些条件时显示特定的属性列表。

以下代码在我将其打印到控制台或使用document.write时执行了我想要的操作。

var people = [{ 
    firstName: 'John',
    lastName: 'Doe',
    age: 23,
    },{ 
    firstName: 'Jane',
    lastName: 'Doe',
    age: 53,
    }]

    for(i = 0; i < people.length; i++){
        if(people[i].age < 65){
            document.write(people[i].firstName + ' ' + 
            people[i].lastName + ' has printed to document. <br>');             
        }
    }

但是当我使用document.getElementById在浏览器中运行代码时,只显示最后一项。

for(i = 0; i < people.length; i++){
    if(people[i].age < 65){
        result = 'Only ' + people[i].firstName + ' ' + 
            people[i].lastName + ' is printed to document. Why?';               
    }
}
document.getElementById('names').innerHTML = result;

有人可以向我解释为什么所有项目都使用document.write显示? 虽然使用document.getElementById时只显示最后一项?

1 个答案:

答案 0 :(得分:3)

问题出在这一行:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import Qt.labs.folderlistmodel 2.1
ApplicationWindow {
visible: true
width: 640
height: 600
title: qsTr("Hello World")
SwipeView {
    id: swipeView
    anchors.fill: parent
    Page {
        Rectangle{
            id: rect1
            color: "#cccccc"
            anchors{top: parent.top; horizontalCenter: parent.horizontalCenter}
            width: parent.width * 0.6
            height: parent.height*0.9

            FolderListModel{
                id: progfolder
                showDirs: true
                showDirsFirst: true
                folder: "file://quatro/visao/qml/reportDialog"                        // It does not work
                //folder: "file:///programming/comm5-qt5.6/visao/test/qml/reportDialog" // It works
                //folder: "file:///programming/comm5-qt5.6/visao/reportDialog.lnk"        // It works
                nameFilters: ["*.qml"]
                Component.onCompleted: console.log("folder " + folder)
            }

            ListView{
                id: lv
                anchors.fill: parent
                model: progfolder
                delegate: progDelegate
            }

            Component{
                id: progDelegate

                Text{
                    text: fileName
                }
            }
        }
    }
}}

因为您要将消息字符串分配给result = 'Only ' + people[i].firstName + ' ' + people[i].lastName + ' is printed to document. Why?'; 变量。由于您位于resultloop变量只会保留最后一个值。

您必须resultconcat变量发送消息。

result

此外,您可以使用for(i = 0; i < people.length; i++){ if(people[i].age < 65){ result += 'Only ' + people[i].firstName + ' ' + people[i].lastName + ' is printed to document. Why?'; } } 格式化邮件。

string templates