I want to list an array in a discord message. I've got the following code so far:
message.channel.send("Game is starting with " + playerNumber + " Players! \n"
+ memberIDs.forEach(element => ("<#" + element + "> \n")));
The memberIDs array contains all IDs from member in a specific channel, now I want to put all member who are in the channel into a message. I've tried it with the code above but it only gives me the message:
Game is starting with *playerNumber* Players!
undefined
I don't really understand why it is undefined because it also would give me the memberIDs in a console log or when I make a forEach loop with messages that get created for every memberID.
The Array in the console.log locks like the following:
[ '392776445375545355', '849388169614196737' ]
I appreciate any help.
short answer
forEach() is not your friend; you need to map() and join()
long answer
the undefined is the result of the forEach() invocation which does not return anything.
so you need to get an string instead.
to do so, you may use .map() which returns an array; and .join() that joins an array of strings into an string.
something like this:
memberIDs.map(element => "<#" + element + ">" ).join('\n');
forEach iterates over an array and doesn't return anything. Use map instead with join:
message.channel.send("Game is starting with " + playerNumber + " Players! \n"
+ memberIDs.map(element => `<#${element}>`).join('\n')
);
Array#map() returns an array of return values from the callback, while Array#forEach() returns undefined. Use .map()
memberIDs.map(m => `<#${m}>`)
.join("\n") // join each element with a newline
forEach doesn't return anything in JavaScript, meaning that memberIDs.forEach(element => ("<#" + element + "> \n"))) will always be undefined.
let idString = "";
memberIDs.forEach(element => (idString = idString + "<#" + element + "> \n"))
message.channel.send("Game is starting with " + playerNumber + " Players! \n"
+ idString);
What this code does is it defines a variable outside of the forEach loop, and then appends strings to it each time the loop runs.
Related
This is the way I add an element to my array
assets.push(house_location + " " + "Cost" + " " + cost + " " + "Downpay"+ " " + downpay)
Now I'm looking for a way to delete that same specific element from my array. Does someone know the code for this? So basically, the opposite of array.push
What you are looking for is the splice method.
If you want to remove the last item you pushed, use assets.pop(). If you want to remove that exact item like you said, you could do something like this:
assets.filter(d => d !== house_location + " " + "Cost" + " " + cost + " " + "Downpay"+ " " + downpay)
I'm guessing you are looking for these methods.
Array.shift() // Removes the first item from an array, and then returns the item removed.
Array.pop() // Removes the last item from an array, and then returns the item removed.
Array.splice() // I really can't be bothered to explain this one, so look at the link below.
The splice method.
What I am trying to achieve is that whenever a new client is added to the clients array, I want the function to return "Welcome (new customer name), you are (his position in the array) in line."
What am I doing wrong? I am trying to get the index of the new client to add 1 so that it starts to count from 1.
let clients = ['Smith', 'Stebve', 'John']
function clientQue(array, newCustomer) {
array.splice(1, 0, newCustomer)
return "Welcome " + newCustomer + ", you are number " + parseInt(array.indexOf('newCustomer')) + 1 + " in line.";
}
clientQue(clients, 'Bob');
You are missing paranthesis () to break out of the string concatenation and do the math first
"Welcome " + newCustomer + ", you are number " + (array.indexOf(newCustomer) + 1 ) + " in line.";
Since you're using array.splice to insert at the 1st index position always, you could also remove all the array.indexOf and always simply output 1 though.
This will work for you (I always like using `` when concating strings
let clients = ['Smith', 'Stebve', 'John']
function clientQue(array, newCustomer) {
array.splice(1, 0, newCustomer)
return `Welcome ${newCustomer} you are number ${parseInt(array.indexOf(newCustomer)) + 1} in line.`;
}
let message = clientQue(clients, 'Bob');
console.log(message)
This is the output
Welcome Bob you are number 2 in line.
Remove the quotes in this part from newCustomer. Needs to be evaluated to 'Bob'.
parseInt(array.indexOf(newCustomer))
You could unshift the new client and take the retuend new lenght of the array as value.
function clientQue(array, newCustomer) {
return "Welcome " + newCustomer + ", you are number " + array.unshift(newCustomer) + " in line.";
}
let clients = ['Smith', 'Stebve', 'John']
console.log(clientQue(clients, 'Bob'));
let clients = ['Smith', 'Stebve', 'John']
function clientQue(array, newCustomer) {
return "Welcome " + newCustomer + ", you are number " + (parseInt([...array, newCustomer].indexOf(newCustomer)) + 1) + " in line.";
}
clientQue(clients, 'Bob');
This should return what you need, however Array.splice mutates the original array, which means it also modifies the values of the original array. It can be harmful to change values of the given parameter.
[...array]
creates a new array from the old array's elements and
[...array, newCustomer]
pushes the new element inside the new array.
Reposting my answer since it was deleted and I wasn't given a chance to update it
A couple things:
Calling .splice removes an element from the array, and based on your question it doesn't seem like that is the desired result.
Furthermore, you don't need to call array.indexOf() because the length of the array will be the position of the newly added client.
You can have a function that takes a name such as "Jeff", adds it to the client array, and then returns the welcome message. Here is an example.
var clients = ["bob", "jane", "isaac", "harry"];
function addClient(name) {
clients.push(name);
return "Welcome " + name + " you are position " + clients.length + " in array";
}
console.log(addClient("Jeff"));
As clients is a queue, I think you would like to put the new customer to the front of the array, so you should use index 0 in splice. i.e.
array.splice(0, 0, newCustomer);
If you would like to put the newCustomer at the back, you may use push() instead. (I prefer using push() actually.)
array.indexOf() should return a number, so you do not need to use parseInt().
However, as you are using string operations before incrementing the index, you should use parenthesis for the addition operation. i.e.
'Welcome ' +
newCustomer +
', you are number ' +
(array.indexOf(newCustomer) + 1) +
' in line.'
Note: As Bob is the new customer at the end of the queue, you may need to change the index calculation to: (array.length - array.indexOf(newCustomer)) instead.
Let's put them together,
let clients = ['Smith', 'Stebve', 'John'];
function clientQue(array, newCustomer) {
array.splice(0, 0, newCustomer);
return (
'Welcome ' +
newCustomer +
', you are number ' +
(array.indexOf(newCustomer) + 1) +
' in line.'
);
}
const q = clientQue(clients, 'Bob');
console.log(q); // Welcome Bob, you are number 1 in line.
console.log(clients); // [ 'Bob', 'Smith', 'Stebve', 'John' ]
I am writing a script to take a stock number, loop through existing stock numbers until a match is NOT found, then assign that unique stock number to the record. My problem is that the usual data[i][2] doesn't seem to reference a 'query' the same way that Apps Script would reference an array.
Fair warning, I'm trying to expand my Apps Script skills in to broader Javascript so I there's a good chance I'm doing it all wrong - I'm all ears if you tell me I'm doing this all incorrectly!
Using the log: data[i][2] gives me 'undefined' whereas data[2] gives me all fields of the third item in my query. Based on this I feel like I just need to learn how to reference it properly.
//Querying my datasource as 'var data'
var query = app.models.UsedVehicles.newQuery();
query.filters.ParentDealType._contains = prefix;
var data = query.run();
//Returns four records which is correct.
var testStockNo = prefix+month+countstring+year;
console.log("Test Stock Number " + j + ": " + testStockNo);
for (i = 0; i < data.length; i++){
console.log("data[i][2]: " + data[i][2]); //results: undefined
console.log("data[2]: " + data[2]); //results: all fields of 3rd query result.
if(data[i][2] === testStockNo){
k++;
break;
}else{
console.log("No Match");
}
}
Even if testStockNo equals the value in field:TStockNo, the log displays:
Test Stock Number 1: C1200118
data[i][2]: undefined
data[2]: Record : { TIndex: 8, TVin8: HS654987, TStockNo: null,
TParentStkNo: GSD6578, TYear: 2010, TMake: NISSAN, TModel: PICKUP,
TMileage: 24356, ParentDealType: C}
No Match
Issue/Solution:
query.run() returns array of records and NOT a array of arrays(2D). You should access the Record value using it's key instead of a index.
Snippets:
console.log("data[i][TStockNo]: " + data[i]['TStockNo']);
console.log("data[i].TStockNo: " + data[i].TStockNo);
console.log("data[2]: " + data[2]);
References:
Query#Run
I have been testing ways to check individual characters in a string for a numeric value. I set up a for loop that goes through them, but when I'm logging it to the console, I get a weird response:
isNumeric: function(n){
for(var i = 0; i < n.length; i++){
console.log("Looping " + i+1);
}
},
So I passed in the value "10" to test it. I get a weird response when I call the function. I get two logs onto the console (like expected), but it says
Looping 01
Looping 11
What is going on here? I didn't think that I was concating strings here, but for some reason it thinks I am? I declared i as an integer var i = 0; and when you increment it by one, what is it doing?
The only other thing I think it must be doing is logging something else appended to Looping 0 and Looping 1, but I don't think that's the case.
If anyone can please help, this is really bugging me and I can't seem to fix it.
Thanks in advance.
+ is left-to-right associative. The expression is evaluated as
('Looping ' + i) + 1
Is it clearer now why string concatenation is performed? If any of the two operands of a + operation is a string, string concatenation is performed. 'Looping ' is a string, hence 'Looping ' + i results in a string.
To change precedence or associativity, you have to use the grouping "operator" ((...)).
You mean console.log("Looping " + (i+1));
The "1" is being appended as a string.
console.log("Looping " + i+1); is being parsed from left to right, as ("Looping " + i) + 1. Add parentheses in the right spot and it should work:
console.log("Looping " + (i+1));
You are concatenating strings, not adding numbers. First, the value of i is cast to a string and concatenated to Looping, resulting in Looping 0. Then, the number 1 is cast to a string and concatenated as well, resulting in what you are seeing: Looping 01.
To get the result you want, you can simply put the i+1 in parentheses.
console.log("Looping " + (i+1));
the problem lies in the line where you do the actual logging :
console.log("Looping " + i+1);
First "Looping " + i happens.
Because "Looping" is a string, i gets cast to a string and appended to "Looping".
The result :
"Looping 0"
Then, the 1 gets added the same way.
"Looping 01"
If you want to keep this from happening, use parenthesis like so :
isNumeric: function(n){
for(var i = 0; i < n.length; i++){
console.log("Looping " + (i+1));
}
},
They are right to add the parentheses, the whole code would be:
isNumeric: function(n){
for(var i = 0; i < n.length; i++){
console.log("Looping " + (i+1));
}
},
Compare your results with this:
n=[1,2,3,4]
function isnum(n){
for(var i = 0; i < n.length; i++){
console.log("Looping " + i+1);
console.log("Looping " + (i+1));
}
}
isnum(n);
This generates the output:
Looping 01
Looping 1
Looping 11
Looping 2
Looping 21
Looping 3
Looping 31
Looping 4
In the statement "Looping " + i+1 what's happening is that "Looping " + i is happening first, i being cast to a string value for the concatenation with "Looping ". The 1 is also being cast as a string value for concatentation. By putting parens around the i+1 we can force (i+1) to happen first as addition before being concatenated, so the output is what you would expect.
I have a Problem with my push function in JavaScript.
<script type="text/javascript">
var myArr = []
var len = myArr.length
$.getJSON('daten.json', function(data) {
$.each(data,function(key,value) {
for(var i = 0; i <= len; i++){
myArr.push("<p>" + value.Name+i ," ", value.Nachname+i + "</p>")
}
})
$('.content').html(myArr.join(''))
})
</script>
I need to convert value.Name+i like this = value.Name0, value.Name1 and so on. I got a JSON File and the Keys are Dynamic, so the first entry got Name0 the second Name1 and so on. Now I must print the JSON file on my html page, but how I can write this line:
myArr.push("<p>" + value.Name+i ," ", value.Nachname+i + "</p>")
with my var i which increment in the loop, to call the Keys in my JSON file?
Like value.Name0. Doing value.Name+i and value.Name.i does not work.
It seems to me what you're looking for is something like this:
myArr.push("<p>" + value['Name'+i] ," ", value['Nachname'+i] + "</p>")
This portion of javascript is covered pretty nicely here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Take the object property in a variable, use condition to check if it has value or not then concat it
var nameval = value.name;
then use in your javascript variable
nameval+i
You need to convert your i (integer value) to string prior to adding it.
use:
value.Name + i.toString()
here's the jfiddle link: http://jsfiddle.net/kpqmp49o/