我想创建一个对象数组,并在满足某些条件时显示特定的属性列表。
以下代码在我将其打印到控制台或使用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
时只显示最后一项?
答案 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?';
变量。由于您位于result
,loop
变量只会保留最后一个值。
您必须result
向concat
变量发送消息。
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