I'm trying to use the parseInt to show only numbers from the following array:
1,2,a,b
Here is my javascript code so far:
var filter_list = ["1,2,a,b"];
function myFunction() {
parseInt(filter_list);
return filter_list;
}
document.getElementById("display").innerHTML = filter_list;
Maybe my idea isn't even going to work. Would love some feedback.
You have array with one element that is string, so you could use join and split and then filter method.
var data = ["1,2,a,b"];
var numbers = data.join(",").split(",").filter(Number);
console.log(numbers)
First, you have to know that each element of the array has to have teir own " ". Like that:
var filter_list = ["1","2","a","b"];
then, if you want to know the elements that are numbres, you can do something like that:
var filter_list = ["1","2","a","b"];
for(i = 0; i < filter_list.length; i++ {
if (!isNaN(ParseInt(filter_list[i])){
var new_array = [];
new_array[i] = filter_list[i];
}
}
document.getElementById("display").innerHTML = new_array;
I don't know if is that what you wanted to know.
As far as I know I'm doing nothing wrong, but it just won't work.
I'm just trying to push a string into a $scope.Array.
This is my code:
var _length = currentNieuws.textImages.length;
for (var i = 0; i < _length; i++) {
var _str = currentNieuws.textImages[i];
$scope.textImages.push(_str);
}
Screenshot of debugging, the string is not empty as you can see:
and as you can see here it is still undefined:
Do you see what I'm doing wrong?
this happens because you get from currentNieuws.textImages and add to $scope.textImages.
And i sure you not init this array in $scope.
Somewhere above you should do $scope.textImages = []
Or yet another variant: avoid loop and do
$scope.textImages = currentNieuws.textImages;
You simply need to define the$scope.textImages before the loop as follow:
$scope.textImages = [];
I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.
i want to pass an array to a function and work on it,but i am afraid ,error occurs saying board_pt is undefined. What is the problem? This is the code :
function set_boardPoint( board_pt,turn)
{
var no = board_pt.number-1;
board[no].row = board_pt.row;
board[no].col = board_pt.col;
board[no].x = board_pt.x;
board[no].y = board_pt.y;
board[no].value = turn;
board[no].number = board_pt.number;
}
board is a global array already defined
The problem is that board_pt have only 1 item, and js in these case know board_pt as object:
function set_boardPoint( board_pt,turn)
{
var no = board_pt.number-1;
if( board[no] != undefined )
{
board[no].row = board_pt.row;
board[no].col = board_pt.col;
board[no].x = board_pt.x;
board[no].y = board_pt.y;
board[no].value = turn;
board[no].number = board_pt.number;
}else
{
board.row = board_pt.row;
board.col = board_pt.col;
board.x = board_pt.x;
board.y = board_pt.y;
board.value = turn;
board.number = board_pt.number;
}
}
If board_pt is a real array, then it's unlikely that it has a property named number. Do you mean length?
From your comments, you have to define the previous_boardPoint as an array. To declare a array in javascript, you need to have - var previous_boardPoint = []; in your code. Also have each elements defined (if you have any) like previous_boardPoint[0] = val1; previous_boarPoint[1] = val2; etc.
If these things are not in your code, then in all likely possibilities, you will get board_pt as undefined in your function set_boardPoint.
A bit of a lengthy title, but I couldn't think of any way to cut it down. What I want to do is see if I can make a prompt function that I can use multiple times to store information for multiple variables. The problem is I want the message in the prompt to change each time so the user knows what I'm asking for. I think there's some way I can pass a a line of text to the function so it knows what to tell the user. Here's roughly what I have so far:
function getNum()
{
var userInput
do
{
userInput = prompt([THIS IS WHERE I WANT THE TEXT TO CHANGE]) * 1;
}while (isNaN(userInput));
return userInput;
}
Any tips?
does this work.
function getNum(message)
{
var userInput
do
{
userInput = prompt(message) * 1;
}while (isNaN(userInput));
return userInput;
}
This will return an array of answers to each question defined in the prompts array.
function getNum() {
var userInput = [];
var prompts = ["Question1","Question2","Question3"];
for( var i = 0; i < prompts.length; i++ ) {
userInput[i] = prompt(prompts[i]);
}
}
Edit: I don't think that's what you're asking for, though.
Well I've found out how do accomplish what I was trying to. Hopefully this will be helpful to anyone in a similar situation.
Here's the function:
function getNum(displayString)
{
var userInput;
do
{
userInput = prompt(displayString,"")*1;
}while(isNaN(userInput));
return userInput;
}
And here's how I passed a string:
Ex)
var userTable = getNum("The first number is the times table");
For some reason the javascript would never be able to execute unless I worded the parameter like this.
Display string is the string I pass to the function, and when I declare and initialize the variable "userTable", I call the function, passing the string in the brackets as the parameter. This is what would play the role of "displayString" in the function.
let lengthofArry = prompt("Talk length of arry");
let newarry = [];
let userdata = 0;
for (let i = 0; i< lengthofArry; i++) {
let userdata = prompt(`Enter Array value ${i+1} `);
userdata = parseInt(userdata)
newarry.push(userdata);
};
console.log(newarry);