问题
I have a string build form comma separated values I use split
to get each value and after that I want to show each value on a new line but what really happens is that I get each value on a new line except of the last two which are shown together on a same line. Just to make it clear:
value1
,value2
,value3
,value4,value5
Here is the function which I'm using:
_checkDates: function(dates) {
if (dates != null)
{
var zzz = dates.split(',');
var xxx = zzz.length;
console.log(xxx);
for (var i=0; i<=xxx; i++)
{
zzz[i] = zzz[i] + '<br />';
return zzz;
}
}
return dates;
}
Just to be clear this is written in ExtJS 4, I'm almost sure that in this case the problem is pure JavaScript and is not related with ExtJS 4 but anyways, maybe I'm wrong.
So any ideas why does it happen and how I could make that last elemnt to get on a new line as well?
Thanks
Leron
回答1:
The for-loop is suspicious. Firstly, you do not process all items (the last one is missing, as @sarfraz pointed out). Sencondly you are returning the result (zzz
) in the for-loop body:
for (var i=0; i<=xxx; i++)
{
zzz[i] = zzz[i] + '<br />';
return zzz; // for-loop will stop here! resulting in ["value1<br />", "Value2", etc...]
}
In Javscript you can simple "join" the array:
return dates.split(',').join("<br />")
Since you are simply replacing strings you could use the replace
method:
return dates.replace(",", "<br />");
回答2:
i have modified your function bit cleaner.since already stefan mentioned your mistake.
function splitDate(dates) {
if (dates != null)
{
var dates = dates.split(',');
var xxx = dates.length;
console.log(xxx);
for (var i=0; i<xxx; i++)
{
dates[i] = dates[i];
}
}
console.log(dates.join('\r\n'));
return dates.join('\r\n');
}
the above function you can do it in a single line:
if it's an array you can split into new line in following way:
var arr = ['apple','banana','mango'];
console.log(arr.join('\r\n'));
if it's a string:
var str = "apple,banana,mango";
console.log(str.split(',').join("\r\n"));
回答3:
Link: https://snack.expo.io/GcMeWpPUX
import React from 'react'
import { SafeAreaView, Text, View, FlatList } from 'react-native'
export default class App extends React.Component {
render() {
return (
<SafeAreaView style={{ flex: 1, alignItems: 'center', justifyContent: 'center',margin:20 }}>
<FlatList
data={your_array_name}
keyExtractor={(item, index) => String(index)}
renderItem={({ item, index }) => {
return (
<Text style={{ color: '#ff8500', fontSize: 18 }}>{item.skills.splice(',').join("\n")}</Text>
)
}}
/>
</SafeAreaView>
)
}
}
const your_array_name = [
{
id: 1,
text: 'Lorem ipsum is simple dummy text for printing the line',
skills: ['javascript', 'java']
},
{
id: 2,
text: 'Lorem ipsum is simple dummy text.',
skills: ['javascript', 'java']
}]
来源:https://stackoverflow.com/questions/10982913/javascript-how-to-show-each-element-of-array-on-a-new-line