Exit recursive function - javascript

I Loop through a complex JSON object but I want to stop the loop after n iterations
n = 0;
maxIterations = 100;
ObjectValues = function(v, k){
if(n == maxIterations){
if (typeof v == "object") {
for (var kp in v) {
if (Object.hasOwnProperty.call(v, kp)) {
ObjectValues(v[kp], k != undefined ? k + "." + kp : kp);
}
}
} else {
console.log(k + ":" + v);
n++;
}
}else{
console.log('I should end the function');
return false;
}
};
But I can't exit the function with return false. The function gets called, even after I tried to exit it with return false.

As I understand it, you want to recursively print maxiteration keys and their values:
n = 0;
maxIterations = 100;
ObjectValues = function(v, k){
if(n < maxIterations){
if (typeof v == "object") {
for (var kp in v) {
if (Object.hasOwnProperty.call(v, kp)) {
if(! ObjectValues(v[kp], k != undefined ? k + "." + kp : kp) )
return false;
}
}
} else {
console.log(k + ":" + v);
n++;
}
return true;
} else {
console.log('I should end the function');
return false;
}
};

Related

create a span inside a div dynamically in vuex

I'm using an existing web app created using vue.js. and below is the code.
function () {
var e = this,
t = e.$createElement,
n = e._self._c || t;
return e.message.text && "human" === e.message.type ? n("div", {
staticClass: "message-text"
}, [e._v("\n " + e._s(e.message.text) + "\n")]) : e.message.text && e.shouldRenderAsHtml ? n("div", {
staticClass: "message-text",
domProps: {
innerHTML: e._s(e.botMessageAsHtml)
}
}) : e.message.text && "bot" === e.message.type ? n("div", {
staticClass: "message-text"
}, [e._v("\n " + e._s(e.shouldStripTags ? e.stripTagsFromMessage(e.message.text) : e.message.text) + "\n")]) : e._e()
}
and here is my n function
function l(e, t) {
function n(e, t, n, i) {
console.log(typeof e + "\t" + typeof t + "\t" + typeof n + "\t" + typeof i);
return function () {
if (n in t) {
return function () {
if (i && "object" === He()(e[n])) {
return f()({}, l(t[n], e[n], i), l(e[n], t[n], i));
}
return function () {
if ("object" === He()(e[n])) {
return f()({}, e[n], t[n]);
}
return t[n];
}();
}();
}
return e[n];
}();
}
var i = arguments.length > 2 && void 0 !== arguments[2] && arguments[2];
return k()(e).map(function (r) {
var o = n(e, t, r, i);
return Ke()({}, r, o);
}).reduce(function (e, t) {
return f()({}, e, t);
}, {});
}
The above code basically creates a div tag with class name as message-text, I want to create a span inside this div. I am not at all good with vue.js and the code seems pretty confusing. please help me out in creating a span inside this div.
This looks like a compiled code and minified probably. But if you can't get the uncompiled version I would try and simplify the code as it has a spaghetti if else.
function(){
var e = this,
t = e.$createElement,
n = e._self._c || t,
result;
if(e.message.text && "human" === e.message.type){
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.message.text) + "\n")])
}else{
if(e.message.text && e.shouldRenderAsHtml){
result = n("div", {staticClass: "message-text",domProps: {innerHTML: e._s(e.botMessageAsHtml)}})
}else{
if(e.message.text && "bot" === e.message.type){
if(e.shouldStripTags){
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.stripTagsFromMessage(e.message.text)) + "\n")])
}else{
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.message.text) + "\n")])
}
} else {
result = e._e();
}
}
}
return result;
}
You probably need to look into function n which is taking the arguments "div" as string and css class as object "message-text" with other props like innerHTML...

ObjectToQuery function return just the properties have values but i want all the properties

I am using this method in order to convert an Object to QueryString. QueryString is required for ajax send request.
var objectToQueryString = function(a) {
var prefix, s, add, name, r20, output;
s = [];
r20 = /%20/g;
add = function(key, value) {
// If value is a function, invoke it and return its value
value = (typeof value == 'function') ? value() : (value == null ? "" : value);
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
if (a instanceof Array) {
for (name in a) {
add(name, a[name]);
}
} else {
for (prefix in a) {
buildParams(prefix, a[prefix], add);
}
}
output = s.join("&").replace(r20, "+");
return output;
};
function buildParams(prefix, obj, add) {
var name, i, l, rbracket;
rbracket = /\[\]$/;
if (obj instanceof Array) {
for (i = 0, l = obj.length; i < l; i++) {
if (rbracket.test(prefix)) {
add(prefix, obj[i]);
} else {
buildParams(prefix + "%" + (typeof obj[i] === "object" ? i : "") + "%", obj[i], add);
}
}
} else if (typeof obj == "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "%" + name + "%", obj[name], add);
}
} else {
// Serialize scalar item.
add(prefix, obj);
}
}
The following code convert the object to QueryString sucessfully but the properties with no values are omitted in the return QueryString. But i want all the properties of the object. It does not matter the object properties have value or not.
If you pass a property where the value is null, then the 'obj' parameter in this call will be null:
function buildParams(prefix, obj, add) {
Can you test your results when you change your 'buildParams' function to this:
function buildParams(prefix, obj, add) {
obj = obj || "";
var name, i, l, rbracket;
rbracket = /\[\]$/;
if (obj instanceof Array) {
for (i = 0, l = obj.length; i < l; i++) {
if (rbracket.test(prefix)) {
add(prefix, obj[i]);
} else {
buildParams(prefix + "%" + (typeof obj[i] === "object" ? i : "") + "%", obj[i], add);
}
}
} else if (typeof obj == "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "%" + name + "%", obj[name], add);
}
} else {
// Serialize scalar item.
add(prefix, obj);
}
}

Where does this unspecified error comes from?

I'm trying to format any kind of variables to achieve some kind of toString() method.
It's working for pretty complex objects and arrays, handling circular references, but when I try to call it on a jQuery object: format($("body")), for testing it on large complex objects, I got this error:
Unhandled exception at line 330, column 21 in ms-appx://8b94d51c-586e-4f3f-bb9c-fa75d62508cd/js/default.js
0x80004005 - Erreur d’exécution JavaScript: Erreur non spécifiée.
0x80004005 - JavaScript Run-time Error: Unspecified error. // I translated it for you
Here is my code (with a // ERROR! comment next to the line 330):
function format(arg, parents, indent) {
var maxParent = 25;
if (parents === undefined) {
parents = [];
}
if (indent === undefined) {
indent = 1;
}
if (contains(parents, arg)) {
return '<span class="brackets">[Circular]</span>';
}
if (typeof arg === 'string' && parents.length > 0) {
return '"' + htmlEntities(arg) + '"';
} else if (Array.isArray(arg)) {
parents.push(arg);
if (parents.length >= maxParent) {
return '<span class="brackets">[Array]</span>';
}
var ret = "[ ";
for (var i = 0, len = arg.length; i < len; i++) {
if (i !== 0) {
ret += ", ";
}
ret += "<br>";
ret += addIndent(indent);
ret += format(arg[i], parents, indent + 1);
}
ret += "<br>";
ret += addIndent(indent - 1);
ret += " ]";
return ret;
} else if (arg === null) {
return '<span class="void">null</span>';
} else if (arg === void 0) {
return '<span class="void">undefined</span>';
} else if (typeof arg === 'number' && (isNaN(arg) || !isFinite(arg))) {
return '<span class="void">' + arg.toString() + '</span>';
} else if (typeof arg === 'object' && arg !== null) {
if (parents.length >= maxParent) {
return '<span class="brackets">[Object]</span>';
} else {
parents.push(arg);
}
var ret = "{";
var first = true;
for (var key in arg) {
if (!first) {
ret += ", ";
}
else {
first = false;
}
ret += "<br>";
ret += addIndent(indent);
ret += key;
ret += ": ";
if (typeof arg[key] === 'function') {
ret += '<span class="brackets">[Function]</span>';
} else {
ret += format(arg[key], parents, indent + 1); // ERROR!
}
}
ret += "<br>";
ret += addIndent(indent - 1);
ret += "}";
remove(parents, arg);
return ret;
}
return arg;
}
Do you have any ideas why this error is occuring?
What can I do to fix it?
Out of the top of my head I can think that arg[key] is null by the time you call the format function. Synchronize the if statement so it executes only after arg[key] is not null.

Uncaught SyntaxError: Unexpected token

I have following script which is used to post comments. But when I try to submit the comment Google Chrome throws this error:
Uncaught SyntaxError: Unexpected token <
jax.processResponse
xmlhttp.onreadystatechange
I simply don't know what this error is all about.
function Jax() {
var loadingTimeout = 400;
var iframe;
this.loadingFunction = function () {};
this.doneLoadingFunction = function () {};
this.stringify = function (arg) {
var c, i, l, o, u, v;
switch (typeof arg) {
case "object":
if (arg) {
if (arg.constructor == Array) {
o = "";
for (i = 0; i < arg.length; ++i) {
v = this.stringify(arg[i]);
if (o && (v !== u)) {
o += ","
}
if (v !== u) {
o += v
}
}
return "[" + o + "]"
} else {
if (typeof arg.toString != "undefined") {
o = "";
for (i in arg) {
v = this.stringify(arg[i]);
if (v !== u) {
if (o) {
o += ","
}
o += this.stringify(i) + ":" + v
}
}
return "{" + o + "}"
} else {
return
}
}
}
return "";
case "unknown":
case "undefined":
case "function":
return u;
case "string":
arg = arg.replace(/"/g, '\\"');
l = arg.length;
o = '"';
for (i = 0; i < l; i += 1) {
c = arg.charAt(i);
if (c >= " ") {
if (c == "\\" || c == '"') {
o += "\\"
}
o += c
} else {
switch (c) {
case '"':
o += '\\"';
break;
case "\b":
o += "\\b";
break;
case "\f":
o += "\\f";
break;
case "\n":
o += "\\n";
break;
case "\r":
o += "\\r";
break;
case "\t":
o += "\\t";
break;
default:
c = c.charCodeAt();
o += "\\u00";
o += Math.floor(c / 16).toString(16);
o += (c % 16).toString(16)
}
}
}
return o + '"';
default:
return String(arg)
}
};
this.getRequestObject = function () {
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
var msxmlhttp = new Array("Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP");
for (var i = 0; i < msxmlhttp.length; i++) {
try {
http_request = new ActiveXObject(msxmlhttp[i])
} catch (e) {
http_request = null
}
}
}
}
if (!http_request) {
alert("Unfortunatelly you browser doesn't support this feature.");
return false
}
return http_request
};
this.$ = function (sId) {
if (!sId) {
return null
}
var returnObj = document.getElementById(sId);
if (!returnObj && document.all) {
returnObj = document.all[sId]
}
return returnObj
};
this.addEvent = function (obj, type, fn) {
if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj[type + fn] = function () {
obj["e" + type + fn](window.event)
};
obj.attachEvent("on" + type, obj[type + fn])
} else {
obj.addEventListener(type, fn, false)
}
};
this.removeEvent = function (obj, type, fn) {
if (obj.detachEvent) {
obj.detachEvent("on" + type, obj[type + fn]);
obj[type + fn] = null
} else {
obj.removeEventListener(type, fn, false)
}
};
this.submitITask = function (comName, func, postData, responseFunc) {
var xmlReq = this.buildXmlReq(comName, func, postData, responseFunc, true);
this.loadingFunction();
if (!this.iframe) {
this.iframe = document.createElement("iframe");
this.iframe.setAttribute("id", "ajaxIframe");
this.iframe.setAttribute("height", 0);
this.iframe.setAttribute("width", 0);
this.iframe.setAttribute("border", 0);
this.iframe.style.visibility = "hidden";
document.body.appendChild(this.iframe);
this.iframe.src = xmlReq
} else {
this.iframe.src = xmlReq
}
};
this.extractIFrameBody = function (iFrameEl) {
var doc = null;
if (iFrameEl.contentDocument) {
doc = iFrameEl.contentDocument
} else {
if (iFrameEl.contentWindow) {
doc = iFrameEl.contentWindow.document
} else {
if (iFrameEl.document) {
doc = iFrameEl.document
} else {
alert("Error: could not find sumiFrame document");
return null
}
}
}
return doc.body
};
this.buildXmlReq = function (comName, func, postData, responseFunc, iframe) {
var xmlReq = "";
if (iframe) {
xmlReq += "?"
} else {
xmlReq += "&"
}
xmlReq += "option=" + comName;
xmlReq += "&no_html=1";
xmlReq += "&task=azrul_ajax";
xmlReq += "&func=" + func;
xmlReq += "&" + jax_token_var + "=1";
if (postData) {
xmlReq += "&" + postData
}
return xmlReq
};
this.submitTask = function (comName, func, postData, responseFunc) {
var xmlhttp = this.getRequestObject();
var targetUrl = jax_live_site;
xmlhttp.open("POST", targetUrl, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
jax.doneLoadingFunction();
jax.processResponse(xmlhttp.responseText)
} else {}
}
};
var id = 1;
var xmlReq = this.buildXmlReq(comName, func, postData, responseFunc);
this.loadingFunction();
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(xmlReq)
};
this.processIResponse = function () {
jax.doneLoadingFunction();
var resp = (this.extractIFrameBody(this.iframe).innerHTML);
resp = resp.replace(/</g, "<");
resp = resp.replace(/>/g, ">");
resp = resp.replace(/&/g, "&");
resp = resp.replace(/"/g, '"');
resp = resp.replace(/'/g, "'");
this.processResponse(resp)
};
this.BetterInnerHTML = function (o, p, q) {
function r(a) {
var b;
if (typeof DOMParser != "undefined") {
b = (new DOMParser()).parseFromString(a, "application/xml")
} else {
var c = ["MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];
for (var i = 0; i < c.length && !b; i++) {
try {
b = new ActiveXObject(c[i]);
b.loadXML(a)
} catch (e) {}
}
}
return b
}
function s(a, b, c) {
a[b] = function () {
return eval(c)
}
}
function t(b, c, d) {
if (typeof d == "undefined") {
d = 1
}
if (d > 1) {
if (c.nodeType == 1) {
var e = document.createElement(c.nodeName);
var f = {};
for (var a = 0, g = c.attributes.length; a < g; a++) {
var h = c.attributes[a].name,
k = c.attributes[a].value,
l = (h.substr(0, 2) == "on");
if (l) {
f[h] = k
} else {
switch (h) {
case "class":
e.className = k;
break;
case "for":
e.htmlFor = k;
break;
default:
e.setAttribute(h, k)
}
}
}
b = b.appendChild(e);
for (l in f) {
s(b, l, f[l])
}
} else {
if (c.nodeType == 3) {
var m = (c.nodeValue ? c.nodeValue : "");
var n = m.replace(/^\s*|\s*$/g, "");
if (n.length < 7 || (n.indexOf("<!--") != 0 && n.indexOf("-->") != (n.length - 3))) {
b.appendChild(document.createTextNode(m))
}
}
}
}
for (var i = 0, j = c.childNodes.length; i < j; i++) {
t(b, c.childNodes[i], d + 1)
}
}
p = "<root>" + p + "</root>";
var u = r(p);
if (o && u) {
if (q != false) {
while (o.lastChild) {
o.removeChild(o.lastChild)
}
}
t(o, u.documentElement)
}
};
this.processResponse = function (responseTxt) {
var result = eval(responseTxt);
for (var i = 0; i < result.length; i++) {
var cmd = result[i][0];
var id = result[i][1];
var property = result[i][2];
var data = result[i][3];
var objElement = this.$(id);
switch (cmd) {
case "as":
if (objElement) {
eval("objElement." + property + "= data ; ")
}
break;
case "al":
if (data) {
alert(data)
}
break;
case "ce":
this.create(id, property, data);
break;
case "rm":
this.remove(id);
break;
case "cs":
var scr = id + "(";
if (this.isArray(data)) {
scr += "(data[0])";
for (var l = 1; l < data.length; l++) {
scr += ",(data[" + l + "])"
}
} else {
scr += "data"
}
scr += ");";
eval(scr);
break;
default:
alert("Unknow command: " + cmd)
}
}
};
this.isArray = function (obj) {
if (obj) {
return obj.constructor == Array
}
return false
};
this.buildCall = function (comName, sFunction) {};
this.icall = function (comName, sFunction) {
var arg = "";
if (arguments.length > 2) {
for (var i = 2; i < arguments.length; i++) {
var a = arguments[i];
if (this.isArray(a)) {
arg += "arg" + i + "=" + this.stringify(a) + "&"
} else {
if (typeof a == "string") {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
} else {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
}
}
}
}
if (jax_site_type == "1.5") {
this.submitTask(comName, sFunction, arg)
} else {
this.submitITask(comName, sFunction, arg)
}
};
this.call = function (comName, sFunction) {
var arg = "";
if (arguments.length > 2) {
for (var i = 2; i < arguments.length; i++) {
var a = arguments[i];
if (this.isArray(a)) {
arg += "arg" + i + "=" + this.stringify(a) + "&"
} else {
if (typeof a == "string") {
a = a.replace(/"/g, """);
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
} else {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
}
}
}
}
this.submitTask(comName, sFunction, arg)
};
this.create = function (sParentId, sTag, sId) {
var objParent = this.$(sParentId);
objElement = document.createElement(sTag);
objElement.setAttribute("id", sId);
if (objParent) {
objParent.appendChild(objElement)
}
};
this.remove = function (sId) {
objElement = this.$(sId);
if (objElement && objElement.parentNode && objElement.parentNode.removeChild) {
objElement.parentNode.removeChild(objElement)
}
};
this.getFormValues = function (frm) {
var objForm;
objForm = this.$(frm);
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt) {
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from
}
}
return -1
}
}
var postData = new Array();
if (objForm && objForm.tagName == "FORM") {
var formElements = objForm.elements;
var assCheckbox = new Array();
var assCntIdx = 0;
var arrayHiddenValues = new Array();
var arrayHiddenCount = 0;
if (formElements.length > 0) {
for (var i = 0; i < formElements.length; i++) {
if (!formElements[i].name) {
continue
}
if (formElements[i].type && (formElements[i].type == "radio" || formElements[i].type == "checkbox") && formElements[i].checked == false) {
continue
}
var name = formElements[i].name;
if (name) {
if (formElements[i].type == "select-multiple") {
postData[i] = new Array();
for (var j = 0; j < formElements[i].length; j++) {
if (formElements[i].options[j].selected === true) {
var value = formElements[i].options[j].value;
postData[i][j] = new Array(name, encodeURIComponent(value))
}
}
} else {
if (formElements[i].type == "checkbox") {
if (assCheckbox.indexOf(formElements[i].name) == -1) {
assCheckbox[assCntIdx] = formElements[i].name;
assCntIdx++
}
} else {
if (formElements[i].type == "hidden") {
if (arrayHiddenValues.indexOf(formElements[i].name) == -1) {
arrayHiddenValues[arrayHiddenCount] = formElements[i].name;
arrayHiddenCount++
}
} else {
var value = formElements[i].value;
value = value.replace(/"/g, """);
postData[i] = new Array(name, encodeURIComponent(value))
}
}
}
}
}
}
if (arrayHiddenValues.length > 0) {
for (var i = 0; i < arrayHiddenValues.length; i++) {
var hiddenElement = document.getElementsByName(arrayHiddenValues[i]);
if (hiddenElement) {
if (hiddenElement.length > 1) {
var curLen = postData.length;
postData[curLen] = new Array();
for (var j = 0; j < hiddenElement.length; j++) {
var value = hiddenElement[j].value;
value = value.replace(/"/g, """);
postData[curLen][j] = new Array(arrayHiddenValues[i], encodeURIComponent(value))
}
} else {
var value = hiddenElement[0].value;
value = value.replace(/"/g, """);
postData[postData.length] = new Array(arrayHiddenValues[i], encodeURIComponent(value))
}
}
}
}
if (assCheckbox.length > 0) {
for (var i = 0; i < assCheckbox.length; i++) {
var objCheckbox = document.getElementsByName(assCheckbox[i]);
if (objCheckbox) {
if (objCheckbox.length > 1) {
var tmpIdx = 0;
var curLen = postData.length;
postData[curLen] = new Array();
for (var j = 0; j < objCheckbox.length; j++) {
if (objCheckbox[j].checked) {
var value = objCheckbox[j].value;
value = value.replace(/"/g, """);
postData[curLen][j] = new Array(assCheckbox[i], encodeURIComponent(value));
tmpIdx++
}
}
} else {
if (objCheckbox[0].checked) {
var value = objCheckbox[0].value;
value = value.replace(/"/g, """);
postData[postData.length] = new Array(assCheckbox[i], encodeURIComponent(value))
}
}
}
}
}
}
return postData
}
}
function jax_iresponse() {
jax.processIResponse()
}
var jax = new Jax();
Please help me.
I'm not sure anyone should read obfuscated, minified code, but i found this:
**xmlhttp.onreadystatechange**=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
jax.doneLoadingFunction();
**jax.processResponse**(xmlhttp.responseText)}
else{}
}
};
Which returns a js error on line 1 :))
Are you allowed to use ** with variable names in js?
check if your bug is not here line 296
var result = eval(responseTxt);
What are you getting as a response? is it html, json?
Check also for notices in your backend script,
You can check this with the console/inspector in chrome (f12) , network tab.
It could be even be a debug output/notice/error from your backend script.
If you open it with firefox, i think firebug shows you a JSON tab if your response is in correct json format.

null value trips up loop

Every time I pass an array to this function, when it hits a null or undefined value it stops the loop. I can't work out how to fix this. When I ask whether the current item in the loop is null or undefined or false, it doesn't answer...
function xul(func, loc, arr){
var elem;
var props = {};
for (var i = 0, len = arr.length; i < len; i++){
if (arr[i] == undefined) {
jsdump("undefined" + " - " + len);
}
else if (arr[i] == null) {
jsdump("null" + " - " + len);
}
else if (arr[i] == false) {
jsdump("false" + " - " + len);
}
else if (typeof arr[i] == "string"){
elem = arr[i];
if (typeOf(arr[i + 1]) == "object") {
props = arr[i+1];
i++;
}
loc = createNode(func, loc, elem, props);
}
if (typeOf(arr[i + 1]) == "array") {
xul("append", loc, arr[i+1]);
} else {
return loc;
}
}
}
What is going on here?
Actually the loop stops here (if you return something you exit the loop!):
if (typeOf(arr[i + 1]) == "array") {
xul("append", loc, arr[i+1]);
} else {
return loc;
}
if the next element it's not an array it returns loc and the loop stops. check this fiddle: http://jsfiddle.net/g8SVJ/ it logs two undefined and then returns loc
You should also use === instead of ==

Categories

Resources